在mysql/multiple文件上传中更新表的同时遍历列名



这是我的代码,用于上传名称为img0、img1、img2、img3等的列中的多个图像。如何通过迭代列名来更新表?我需要连接吗?

if(isset($_POST['submit'])){        
$uploadsDir = "images/property/";
$allowedFileType = array('jpg','png','jpeg');
$error="";
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
$total= count($_FILES['fileUpload']['name']);
if($total > 6){
$error="please select less than 6 pictures";
}
// Loop through file items
for($i=0; $i<$total; $i++){
// Get files upload path
$fileName        = $_FILES['fileUpload']['name'][$i];
$tempLocation    = $_FILES['fileUpload']['tmp_name'][$i];
$targetFilePath  = $uploadsDir . $fileName;
$fileType        = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$uploadOk = 1;
if(in_array($fileType, $allowedFileType)){
if(move_uploaded_file($tempLocation, $targetFilePath)){
$sqlVal = "('".$fileName."')";
} else {
$error="uploading error";
}
} else {
$error="please select valid image";
}
// Add into MySQL database
if(!empty($sqlVal)) {
//the problem is here????????   
$insert = $conn->query("UPDATE property (img???) VALUES $sqlVal");
if($insert) {
$error="success";
} else {
$error="database error";
}
}
}
} else {
$error="please select  pictures to upload";
}
} 

我的表中有一列的名称为img0、img1、img2、img3、img4。我想更新特定列中的每个图像,我可以用循环来完成吗

这是一个起点。由于问题中没有包含足够的信息,您需要进行一些更改。

$query = 'UPDATE property set ';
if(empty($_FILES['fileUpload']['name']) || !is_array($_FILES['fileUpload']['name'])) {
exit('Invalid Update');
} else {
foreach($_FILES['fileUpload']['name'] as $key => $value){
$query .= ' img' . $key . ' = ?, ';
}
}
$query = rtrim($query, ', ');
$query .= ' WHERE ... = ?'; <--- fix this (Don't replace the ?, that is placeholder for value that the column should equal)
$insert = $conn->prepare($query);
$params = array_merge($_FILES['fileUpload']['name'], array('WHERE IDENTIFER')); <--- fix this
$stmt->bind_param(str_repeat('s', count($_FILES['fileUpload']['name']) . 's(WHERE DATA TYPE HERE)', ...$params); <-- fix this
$stmt->execute();

其他注意事项:

这种数据库设计稍后会引起问题。参见:

https://en.wikipedia.org/wiki/First_normal_form

你应该做的不仅仅是检查扩展名来验证文件的完整性/安全性:

完整的安全图像上传脚本

(如果未查看完整答案,请导航至instead of just relying on the Content-type header以获取有关文件扩展名的位(

有关MySQLi准备语句的更多信息,请参阅https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php.如果刚开始,你可能会考虑PDO。它可以跨多个数据库系统使用,并且创建/执行准备好的语句所需的代码更少。检索数据时要少得多,执行过程也比MySQLi清晰得多。

最新更新