-2

I am trying to insert into two tables the mother table and the child table : but the mother table gets the data and the child table does not : I get the error Cannot add or update a child row: a foreign key constraint fails (portfolio.players, CONSTRAINT players_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE) And bellow is my code :

$query="INSERT INTO users(email,date)
VALUES('$email','$date')";
$user_result = mysql_query($query); 
/*last inserted Id */
$id_last = ("SELECT LAST_INSERT_ID()");
$res = mysql_query($id_last);
$last_id = mysql_fetch_array($res);
/*last inserted Id  ends*/
/*insert query */
$sql="INSERT INTO 
players(name, surname, position, contact_number, email, username, password, date, user_id)
VALUES('$name ','$surname','$position','$contact_number','$email','$username','$password', '$date', '$last_id')";
$result = mysql_query($sql)or die (mysql_error()); 
/*if something goes wrong then tell the user*/ 
if($result){
echo "Player Successfully added</br>";

}
else {
echo "We are sorry no player inserted ";
}
4

1 回答 1

2
$last_id = mysql_fetch_array($res);

mysql_fetch_array返回数组,以获取您应该使用的实际 id $last_id[0]。还有一个功能:mysql_insert_id。在查看链接的手册页时,请注意大红框,并继续使用 mysqli 或 PDO 进行开发。

于 2013-05-05T15:24:29.950 回答