简体   繁体   English

在多个表中添加记录PHP MYSQL

[英]Adding records in multiple tables PHP MYSQL

I have two tables, users and comments. 我有两个表,用户和评论。 I need to add firstname and lastname to users and the comments to the comments table with the user id as a foreign key in comments. 我需要在注释中将firstname和lastname添加到users并将注释添加到comments表中,并将用户id作为外键。 I am using phpmyadmin to do the add the foreign key constrain and relationships. 我正在使用phpmyadmin来添加外键约束和关系。

This is my html form: 这是我的html表单:

<form action="dbconnect.php" method="post">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br />
Comments: <textarea cols="30" rows="5" name="comments"></textarea><br />
<input type="submit">
</form>

This is my php insert code: 这是我的php插入代码:

mysql_select_db("test", $db_server);

$sql="INSERT INTO users (Firstname, Lastname)
VALUES
('$_POST[firstname]','$_POST[lastname]')";

$sql="INSERT INTO comments (Comment)
VALUES
('$_POST[comments]')";


if (!mysql_query($sql,$db_server))
    {
    die('Error' . mysql_error());   
    }
echo "1 record added" ;

mysql_close($db_server);

and this is the error i'm getting: 这是我得到的错误:

Error: Cannot add or update a child row: a foreign key constraint fails ( test . comments , CONSTRAINT comments_ibfk_2 FOREIGN KEY ( useridfk ) REFERENCES users ( id ) ON DELETE CASCADE ON UPDATE CASCADE) 错误:无法添加或更新子行:外键约束失败( testcomments ,CONSTRAINT comments_ibfk_2 FOREIGN KEY( useridfk )REFERENCES usersid )ON DELETE CASCADE ON UPDATE CASCADE)

I am new to php and phpmyadmin so any help is appreciated. 我是php和phpmyadmin的新手,所以任何帮助都表示赞赏。

First of all, you need to run the INSERT query on the users table so the user record is created. 首先,您需要在users表上运行INSERT查询,以便创建用户记录。

mysql_select_db("test", $db_server);

$sql="INSERT INTO users (Firstname, Lastname)
VALUES
('$_POST[firstname]','$_POST[lastname]')";

mysql_query($sql);

if (!mysql_query($sql,$db_server))
    {
    die('Error' . mysql_error());   
    }
echo "1 record added" ;

You then need to retrieve the id of the newly created record on the users table 然后,您需要在users表中检索新创建的记录的ID

$newIdQuery = mysql_query("SELECT LAST_INSERT_ID() AS userId FROM users");
$newId = mysql_fetch_assoc($newIdQuery);

Then you can use that userId to add the comments, with the user id foriegn key properly populated. 然后,您可以使用该userId添加注释,并正确填充用户ID foriegn键。

Note: When building MySQL queries using the mysql_* functions, if you wrap a php variable in { } it will insert the value of the php variable into the SQL statement. 注意:使用mysql_ *函数构建MySQL查询时,如果在{}中包装php变量,它会将php变量的值插入到SQL语句中。

$sql="INSERT INTO comments (id, Comment)
VALUES
({$newId["userId"]}, '$_POST[comments]')";


if (!mysql_query($sql,$db_server))
    {
    die('Error' . mysql_error());   
    }
echo "1 record added" ;

mysql_close($db_server);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM