如何通过php为UPDATE,INSERT,DELETE上的WHERE子句选择mysql行ID? [英] How to select mysql row ID for WHERE clause on UPDATE, INSERT, DELETE via php?
问题描述
我一直在努力了解如何获取当前用户 ID.能够更新、显示或任何人希望对该行执行的操作.
I've been struggling for a while to understand how to get the current users id. To be able to update, display or whatever one wishes to do to that row.
以下是: 文件上传脚本/按用户 ID、数据库结构和 HTML 查询的更新.
Below is: File upload script / update query by user id, the db structure, and the HTML.
问题:我可以更新行,但是只有当我指定 WHERE id="" 我怎样才能找出当前用户 ID 并使用它来更新 mysql 行?
The Problem: I can update the row, however only if I specify WHERE id="" How can I find out the current users ID and use this to update the mysql row?
php:
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$img_path = ("images/".$file_name);
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
// connect to the database
$servername = 'HOST';
$username = 'USER';
$password = 'PASS';
$dbname = 'TABLE';
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE users SET image_name='$file_name', image_size='$file_size', image_path='$img_path' WHERE user_id=2";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
数据库结构:
`user_id` int(5) NOT NULL AUTO_INCREMENT,
`user_name` varchar(25) NOT NULL,
`user_email` varchar(35) NOT NULL,
`user_pass` varchar(255) NOT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`image_type` varchar(25) NOT NULL,
`image` longblob NOT NULL,
`image_size` varchar(25) NOT NULL,
`image_name` varchar(50) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_email` (`user_email`)
)
HTML:
<form enctype="multipart/form-data" action="" method="post">
<input type="file" name="image">
<input name="upload_img" type="submit" value="Upload image">
</form>
推荐答案
update 语句不会执行,因为表中没有 'image_path' 字段.
The update statement will not execute because there is no 'image_path' field in the table.
这篇关于如何通过php为UPDATE,INSERT,DELETE上的WHERE子句选择mysql行ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!