PHP MySQL查询插入与连接分配变量



我遇到了php插入多个图像和数据库的唯一post-id的问题。在数据库中,我有图像表和帖子表,当我上传多个图像时,图像将与当前帖子id一起存储在图像表中。

问题是插入语法错误,因为

$insertValuesSQL

来自每个使用.=串联分配上传图像的。

问题是,我想添加额外的帖子id,这样我就可以很容易地从帖子id中获得图像,所以我必须插入两个东西,即帖子id中的$insertValuesSQL$last_id

有人能帮我纠正语法并上传带有帖子id的图片吗?再见,谢谢。

错误:

$insert = $conn->query("INSERT INTO test (file_name, post_id) VALUES $insertValuesSQL,$last_id");

PHP完整代码:

$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
$statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
if(!empty(array_filter($_FILES['submit-image']['name']))){
foreach($_FILES['submit-image']['name'] as $key=>$val){
// File upload path
$fileName = basename($_FILES['submit-image']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["submit-image"]["tmp_name"][$key], $targetFilePath)){
// Image db insert sql
$insertValuesSQL .= "('".$fileName."'),";
}else{
$errorUpload .= $_FILES['submit-image']['name'][$key].', ';
}
}else{
$errorUploadType .= $_FILES['submit-image']['name'][$key].', ';
}
}
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
if(!empty($insertValuesSQL)){
$insertValuesSQL = trim($insertValuesSQL,',');
// Insert image file name into database
$insert = $conn->query("INSERT INTO test (file_name, post_id) VALUES $insertValuesSQL,$last_id");
if($insert){
$errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
$errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
$errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
$statusMsg = "Files are uploaded successfully.".$errorMsg;
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}else{
$statusMsg = 'Please select a file to upload.';
}

再添加一个

如果我使用以下代码:

$insert = $conn->query("INSERT INTO test (file_name) VALUES $insertValuesSQL");

成功上传了多个图像,但没有图像的帖子id

引用自:https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/

您需要将$last_id放入要插入的每个值列表中,而不是作为一个单独的参数。但是不能这样做,因为在设置$last_id之前要创建$insertValuesSQL

您可以在设置$last_id之后将创建$insertValuesSQL的循环移动到,但另一种方法是使用MySQL的内置函数LAST_INSERT_ID():

$insertValuesSQL .= "('".$fileName."', LAST_INSERT_ID()),";

然后您可以从稍后的INSERT查询中取出$last_id

$insert = $conn->query("INSERT INTO test (file_name, post_id) VALUES $insertValuesSQL");

相关内容

最新更新