我正在创建一个系统,允许您添加一个消息与多个图片上传。所有图像的上传都很顺利,但是,当我尝试将所有图像位置插入到具有表'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查询在我的代码的底部执行多次,并添加一行与下一个图像的位置到数据库?我已经把它放在foreach中,但是它似乎不起作用。
是的,就像lealhugui说的,您正在插入LAST_INSERT_ID()作为scrapimage中scrap_id的值。您的约束要求在代码中有一行具有相同的id。
在某个地方,可能在这个循环上面,您应该已经弄清楚这一行的scrap_id是什么。
基本上,数据库告诉您"scrap_id"列引用的FK不是一个有效值。你确定你有一个记录在"废料"表上,所以"id"在废料。Scrap_id和scrapimage。Scrap_id能匹配吗?
LAST_INSERT_ID()在第一次迭代中求值为0,您插入带有0的行作为scrap_id。在下一次迭代中,LAST_INSERT_ID()的计算结果为…等等……
0。plus,它只适用于auto_increment列,所以如果scrap_id是autoincrement,你想插入空