无法添加或更新子行:外键约束失败

时间:2010-05-21 22:13:51

标签: php mysql get foreign-keys

// Getting the id of the restaurant to which we are uploading the pictures
$restaurant_id = intval($_GET['restaurant-id']);

if(isset($_POST['submit']))
{
    $tmp_files = $_FILES['rest_pics']['tmp_name'];
    $target_files = $_FILES['rest_pics']['name'];
    $tmp_target = array_combine($tmp_files, $target_files);
    $upload_dir = $rest_pics_path;
foreach($tmp_target as $tmp_file => $target_file)
    {
        if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file))
        {
            $sql = sprintf("
            INSERT INTO rest_pics
            (branch_id, pic_name)
            VALUES ('%s', '%s')"
            , mysql_real_escape_string($restaurant_id)
            , mysql_real_escape_string(basename($target_file)));
            $result = mysql_query($sql) or die(mysql_error());
        }

我收到了下一个错误:

  

无法添加或更新子行:a   外键约束失败   (rest_v2rest_pics,CONSTRAINT   rest_pics_ibfk_1外国钥匙   (branch_id)参考   rest_branchesbranch_id)ON   在更新CASCADE上删除CASCADE

但是,当我在sql查询中直接输入餐馆ID(例如14)而不是$ restaurant_id变量时,这个错误完全消失了,一切顺利。

获取id的URL是: http://localhost/rest_v2/public_html/admin/add-delete-pics.php?restaurant-id=2

请帮忙吗?

2 个答案:

答案 0 :(得分:3)

问题是您的查询将$ restaurant_id作为字符串放入。你引用了它。你想用这个替换它:

 $sql = sprintf("
            INSERT INTO rest_pics
            (branch_id, pic_name)
            VALUES (%s, '%s')" //<-- I removed the quotes around the first %s
            , mysql_real_escape_string($restaurant_id)
            , mysql_real_escape_string(basename($target_file)));

此外,您可能希望使用PDO而不是过时的mysql_ *函数。它们更干净,更安全,更快速,更现代。以下是使用PDO的相同查询:

$statement = $db->prepare('INSERT INTO rest_pics (branch_id, pic_name) VALUES (?, ?)');
$statement->execute(array($restaurant_id, $target_file));

请注意,我没有必要处理担心引号,因为PDO正确地确定了进入的查询和结果的数据类型。此外,默认情况下这是安全的 - 无需手动转义。换句话说,如果您使用PDO,则不会发生这种情况。

答案 1 :(得分:1)

对不起伙计们,我想通了。 错误是在形式中,我用过:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" ...

而不是:

<form action="" ...

这使得页面加载没有其GET参数,因此branch_id丢失了,这就是为什么发生这种狡猾的错误。

非常感谢您的回答:)