如何使用外键将表单数据上载到子表中

时间:2015-06-15 16:00:19

标签: php mysql

我有一个应该将数据插入子表的表单。该表具有指向父表的外键(ADD FOREIGN KEY(userid) REFERENCES users(userid) ON DELETE CASCADE ON UPDATE CASCADE;)。 当用户点击提交时,如何同时插入表单数据和外键?到目前为止,外键正在工作,所有这些都插入到子表中。 这是我的表格:

session_start();
require_once('classes/auth.php');
require_once('includes/connect.php');

$user=$_SESSION['SESS_USERID'];

if($_SERVER["REQUEST_METHOD"] =="POST") {
}
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$place=$_POST['place'];
$overmij=$_POST['overmij'];

// Working like clockwork now
$sql = "INSERT INTO userinfo(firstname,lastname,place,overmij,userid)
VALUES ('$firstname','$lastname','$place','$overmij','$user') ";

// I don't need this because the userid is already in the SESSION
//$sql = "INSERT INTO userinfo (userid) SELECT userid FROM users WHERE //userid='$user'";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

1 个答案:

答案 0 :(得分:1)

您的第一个$sql未被执行。它被覆盖,然后第二个被执行。让第一个也执行。

// This is not working
$sql = "INSERT INTO userinfo(firstname,lastname,place,overmij)
VALUES ('$firstname','$lastname','$place','$overmij') ";

/** EXECUTE YOUR QUERY HERE AS WELL **/
//  $conn->query($sql)

// The following is working:
$sql = "INSERT INTO userinfo (userid) SELECT userid FROM users WHERE userid='$user'";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

修改

根据您的评论,您会收到以下错误:

 INSERT INTO userinfo(firstname,lastname,place,overmij VALUES ('vsdvsdvds','vdsvdsv','ddv','dvdvdv','cscsc','overmij') 

)之前缺少一个问题VALUES

编辑2:

根据您的第二条评论:

您没有在插入查询中添加userid。您说您的会话中已经有userid

是的,你是对的。您不需要两个查询。您可以这样做,如下所示:

INSERT INTO userinfo(userid, firstname,lastname,place,overmij) VALUES ('USERID_FROM_SESSION', 'vsdvsdvds','vdsvdsv','ddv','dvdvdv','cscsc','overmij')