-1

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

在此处输入图像描述

每次我想更新外部表时,我都会给出错误:

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"; 

    };
?>
4

3 回答 3

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());
于 2013-11-08T15:42:10.417 回答
2

您试图在实际插入之前获取插入记录的 id。

您需要移动您的第一个查询执行 -$result=mysql_query($sql)or die(mysql_error());之前$singer_id = mysql_insert_id();

还:

  1. 您的代码容易受到 SQL 注入的影响(正如其他人所指出的)。

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

于 2013-11-08T15:45:06.337 回答
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()));
}

文档

于 2013-11-08T15:55:49.380 回答