如何在多对多关系中更新外键

时间:2013-11-08 15:30:21

标签: php mysql

我是php的新手,我有2个表有多对多关系,另有一个关系表:

enter image description here

每次我想要更新外国表我都会给出错误:

Cannot add or update a child row: a foreign key constraint fails (`wikiseda`.`genre_singer`, CONSTRAINT `genre_singer_ibfk_1` FOREIGN KEY (`f_singer_id`) REFERENCES `singers` (`singerid`) ON DELETE CASCADE ON UPDATE CASCADE);

这是我的代码:

<?php
include('../db_inc.php');
define("UPLOAD_DIR",realpath(dirname(__FILE__)));

$singer_name =$_POST['singer_name'];
$singer_gender=$_POST['singer_gender'];
$singer_des=$_POST['singer_description'];
$singer_genre=$_POST['genre_list'];

    $path = UPLOAD_DIR .'/musics/'.$singer_name;
    if(!file_exists($path)){
        mkdir($path,0777,true);
        }

$sql ="INSERT INTO singers(singer_name,singer_gender,singer_description) VALUES ('$singer_name','$singer_gender','$singer_des')" ;
 $singer_id = mysql_insert_id();
$sql2 =("INSERT INTO genre_singer(f_singer_id,f_genre_id) VALUES ('$singer_id','$singer_genre')");

$result=mysql_query($sql)or die(mysql_error());
$result2=mysql_query($sql2)or die(mysql_error());
if('$result'){
    echo "insert successfully"; 

    };
?>

3 个答案:

答案 0 :(得分:3)

SQL注入漏洞和过度松散的目录权限暂时搁置(尽管你真的应该留意关于它们的评论)。尝试执行第一个查询,然后尝试上次插入id:

$sql ="INSERT INTO singers(singer_name,singer_gender,singer_description) VALUES ('$singer_name','$singer_gender','$singer_des')" ;    
$result=mysql_query($sql)or die(mysql_error());

$singer_id = mysql_insert_id();
$sql2 =("INSERT INTO genre_singer(f_singer_id,f_genre_id) VALUES ('$singer_id','$singer_genre')");
$result2=mysql_query($sql2)or die(mysql_error());

答案 1 :(得分:2)

您试图在插入记录之前获取插入记录的ID。

您需要在$result=mysql_query($sql)or die(mysql_error());之前移动首次查询 - $singer_id = mysql_insert_id();

此外:

  1. 您的代码容易受到SQL注入攻击(正如其他人所说)。

  2. 使用来自用户的任意路径/名称在服务器上创建目录可能是一个坏主意。如果您按照类似的方式创建文件,那么您将允许任何用户在您的服务器上执行任意代码。

答案 2 :(得分:1)

为了完成,这是PDO完成的工作:

// note: untested code follows
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);

$statement = $pdo->prepare('
    INSERT INTO `singers` (
        singer_name,
        singer_gender,
        singer_description
    ) VALUES (
        :singer_name,
        :singer_gender,
        :singer_des
    )
');

$statement->execute(array(
    'singer_name'=>$_POST['singer_name'],
    'singer_gender'=>$_POST['singer_gender'],
    'singer_des'=>$_POST['singer_description']
));
$singer_id = $pdo->lastInsertId();

if (!$singer_id) {
    // tip: do something nicer than die
    die('Error occurred:'.implode(":",$pdo->errorInfo()));
}


$statement = $pdo->prepare('
    INSERT INTO `genre_singer` (
        f_singer_id,
        f_genre_id
    ) VALUES (
        :singer_id,
        :singer_genre
    )
');
$result = $statement->execute(array(
    'singer_id'=>$singer_id,
    'singer_genre'=>$_POST['genre_list']
));

if (!result) {
    // tip: do something nicer than die
    die('Error occurred:'.implode(":",$pdo->errorInfo()));
}

<强>文档