我有一个对话表和对话回复表:
对话表:
+-------+-------+--------+
| cid | u_1 | uid_2 |
+-------+-------+--------+
| 1 | 8 | 3 |
| 2 | 8 | 5 |
| 3 | 8 | 2 |
+-------+-------+--------+
conversation_reply 表:
+-------+-------+--------+--------+
| cr_id | reply | uid_fk | cid_fk |
+-------+-------+--------+--------+
| 1 | | 8 | 1 |
| 2 | | 8 | 11 |
| 3 | | 8 | 11 |
+-------+-------+--------+--------+
如果创建新回复时对话表不存在,我需要能够使用新记录更新对话表,但出现以下错误:
Cannot add or update a child row: a foreign key constraint fails
(`_db`.`conversation_reply`, CONSTRAINT `conversation_reply_ibfk_2`
FOREIGN KEY (`cid_fk`) REFERENCES `conversation` (`cid`))
非常感谢任何帮助!!!!
编辑
我已将 convo 回复查询放入创建新的 convo 查询中,它将创建一个新的 convo 但仍然不插入回复:
if (!empty($_GET['conv_id'])) {
$cid = mysql_real_escape_string($_GET['conv_id']);
echo $cid;
}
if($user_one!=$user_two){
// Check convo doesn't already exist.
$q_exist= mysql_query("SELECT c_id FROM mc_conversation WHERE (user_one='$user_one' and user_two='$user_two') or (user_one='$user_two' and user_two='$user_one') ") or die(mysql_error());
if(mysql_num_rows($q_exist)==0) {
$query = mysql_query("INSERT INTO mc_conversation (user_one,user_two,ip,time) VALUES ('$user_one','$user_two','$ip','$time')") or die(mysql_error());
$q=mysql_query("SELECT c_id FROM mc_conversation WHERE user_one='$user_one' ORDER BY c_id DESC limit 1");
$v=mysql_fetch_array($q);
return $v['c_id'];
$v_cid = $v['c_id'];
// Insert reply.
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$v_cid')") or die(mysql_error());
// Convo already exists.
} else {
$v=mysql_fetch_array($q_exist);
return $v['c_id'];
// Insert reply
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
}
}
最佳答案
您在 else 循环中调用了“return”,这将结束函数的执行,或者如果从全局范围调用,则执行当前脚本。 http://php.net/manual/en/function.return.php 试试这个:
// Insert reply
$v=mysql_fetch_array($q_exist);
$qR= mysql_query("INSERT INTO mc_conversation_reply (user_id_fk,reply,ip,time,c_id_fk) VALUES ('$uid','$reply','$ip','$time','$cid')") or die(mysql_error());
echo $cid;
关于php - SQL 使用 PHP 递归更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26302997/