這是我用于在名稱為 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 的列。我想更新特定列中的每個影像我可以用回圈來做嗎
uj5u.com熱心網友回復:
這是一個起點。您需要進行一些更改,因為問題不包含足夠的資訊。
$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 的要清晰得多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411778.html
標籤:
