我正在创建一个系统,允许您添加包含多个上传图像的消息。但是,当我试图将所有图像位置插入到表“messages”中具有外键的表中时(这样每个图像都知道它属于哪一条消息),就会得到以下错误:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`scrapll`.`scrapimage`, CONSTRAINT `scrapimage_ibfk_1` FOREIGN KEY (`scrap_id`) REFERENCES `scraps` (`scrap_id`))' in C:\xampp\htdocs\scrapll_m_nonstatic\process\new\scrap_process.php:132 Stack trace: #0 C:\xampp\htdocs\scrapll_m_nonstatic\process\new\scrap_process.php(132): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\scrapll_m_nonstatic\process\new\scrap_process.php on line 132
只有当我试图上传多张图片时,才会发生这种情况。当我只上传一张图片时,一点问题都没有。
下面是代码:
foreach($_FILES['scrapPhotos']['tmp_name'] as $key => $tmp_name ){
$fileName = $_FILES['scrapPhotos']['name'][$key];
$fileSize = $_FILES['scrapPhotos']['size'][$key];
$fileTmp = $_FILES['scrapPhotos']['tmp_name'][$key];
$fileType= $_FILES['scrapPhotos']['type'][$key];
if($_FILES['scrapPhotos']['name'][$key]){
// Get file extension of uploaded file
$imgFileExtension = strrchr($fileName, ".");
// Check if file extension of uploaded file is valid
if(!in_array($imgFileExtension, $validFileExtensions)) {
echo $scrapErrors[0];
}
// Check if file size is valid (!> 10000000)
elseif($fileSize > MAXFILESIZE) {
echo $scrapErrors[1];
}
else {
// The path to Scrap image
$imgLoc = "../../../scrapll_m/static/img/user/scrap/orig/";
// Move files to appropiate location
$imgFile = sha1(uniqid($_FILES['scrapPhotos']['name'][$key]));
$imgFilePath = $imgLoc . $imgFile . $imgFileExtension;
// Store image(s) on the server
move_uploaded_file($_FILES['scrapPhotos']['tmp_name'][$key], $imgFilePath);
$insertImgQuery = 'INSERT INTO scrapimage (scrap_id, image_original_size, image_scrap_size)
VALUES (LAST_INSERT_ID(), ?, ?)';
$prepInsertImg = $conn->prepare($insertImgQuery);
$prepInsertImg->execute(array($imgFilePath, $imgFilePath));
}
}
}
那么,为什么我不能将代码底部的SQL查询多次执行,并向数据库中添加一行和下一个图像位置呢?我已经把它放在前头去做了,但它似乎行不通。
发布于 2014-05-19 16:40:52
是的,就像lealhugui所说的,在剪贴图像中插入LAST_INSERT_ID()作为scrap_id的值。您的约束是要求在具有相同id的残余物中有一行。
在某个地方,可能在这个循环的上方,您应该已经知道这一行的scrap_id是什么了。然后对每个剪贴图像使用相同的id。
发布于 2014-05-19 16:38:37
基本上,数据库告诉您"scrap_id“列引用的FK不是有效值。您确定您在“报废”表上有记录以便scrap.scrap_id和scrapimage.scrap_id中的“in”能够匹配吗?
发布于 2014-05-19 16:42:26
LAST_INSERT_ID()在第一次迭代中计算为0,将0作为scrap_id插入行。在下一个loo-迭代中,LAST_INSERT_ID()的计算结果为.再等一次.0。
此外,它只适用于auto_increment列,因此如果scrap_id是自动增量,则要插入NULL。
https://stackoverflow.com/questions/23742798
复制相似问题