使用PHP-MySQL从PK更新FK

时间:2011-07-26 07:33:38

标签: php mysql insert foreign-keys

我是php和mysql的新手 我有个问题 我有2张桌子

<?php
    $insert = mysql_query("INSERT INTO request (date, type_request, subject, customer)
    VALUES (NOW(), '".$type."', '".$subject."', '".$username."')");

    $fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");

?>

我一直在这样做,但仍无法在表格反馈中填写id_request 表的结构就像这样

表格请求

id_request auto_increment not_null,-->PK
date,
type_request,
subject,
customer

表格反馈

id_feedback auto_increment not_null,
id_request,---FK
feedback_user

任何人都可以建议如何更新外键

此致

2 个答案:

答案 0 :(得分:2)

在您的代码中

$fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");

last_insert_id替换为LAST_INSERT_ID()

因为它是MySQL函数而不是字段。

答案 1 :(得分:1)

我知道我会因此受到抨击,但这就是我要做的事情:

<?php
$date       = date('Y-m-d H:i:s');

$req_query  = 'INSERT INTO request (date, type_request, subject, customer) '.
              "VALUES ('$date', '$type', '$subject', '$username')";
$req_result = mysql_query($req_query);

$fk_query   = 'SELECT MAX(id) id FROM request '.
              "WHERE date = '$date' AND type_request = '$type' ".
              "AND subject = '$subject' AND customer = '$username'";
$fk_result  = mysql_query($fk_query);
$fk_row     = mysql_fetch_assoc($fk_result);
$fk         = $fk_row['id'];

$fb_result  = mysql_query("INSERT INTO feedback (id_request) VALUES($fk)");
?>