简体   繁体   English

PHP / SQL:如何使用PHP通过SQL将表单输入插入2个数据库表中?

[英]PHP/SQL: How to insert form input via SQL into 2 database tables with PHP?

I am just starting out with PHP and SQL and I am trying to make a account creation screen for a website in PHP. 我刚开始使用PHP和SQL,并且尝试使用PHP创建网站的帐户创建屏幕。 For this I've created a form file with an action to the second file where the input data from the form is supposed to be inserted into TWO TABLES of a local database. 为此,我创建了一个表单文件,该文件具有对第二个文件的操作,该文件应将来自表单的输入数据插入到本地数据库的两个表中。 (I am using WAMP with phpMyAdmin) - (我将WAMP与phpMyAdmin一起使用)-

My (database) connection is up and everything and I have no errors, and when go to phpMyAdmin and do the SQL statement with dummy data it works, but when the user fills out the form and clicks on next it doesn't get inserted into the database? 我的(数据库)连接已建立,一切正常,并且没有任何错误,当转到phpMyAdmin并使用伪数据执行SQL语句时,它可以工作,但是当用户填写表单并单击下一步时,它不会插入数据库? Anyone have a idea how to fix this? 有人知道如何解决此问题吗?

Here is my current php code where the data is supposed to be inserted into 2 different tables via the SQL statement: 这是我当前的php代码,应该通过SQL语句将数据插入2个不同的表中:

<?php
    $_SESSION['user'] = $_POST['name']; //user naam ophalen van vorige pagina en onthouden voor gehele sessie
$name= $_SESSION['user'];

    $_SESSION['wachtwoord'] = $_POST['access']; 
$access= $_SESSION['wachtwoord'];

    $_SESSION['mail'] = $_POST['email'];
$email= $_SESSION['mail'];

    $_SESSION['huisdier'] = $_POST['pet'];
$pet= $_SESSION['huisdier'];

$savenewuser = "BEGIN; 
                INSERT INTO user (id, naam, email, pass)
                VALUES (NULL, '$name', '$email', '$access');
                INSERT INTO preferences (id, huisdier)
                VALUES (LAST_INSERT_ID(), '$pet');
                COMMIT;
                ROLLBACK;";

mysqli_query($con, $savenewuser);

$result = mysqli_query($con, $savenewuser);
if (!$result) {
echo "Error: Account could not be created, try again later.";
} else { 
echo "Account has been created!";
}

mysqli_close($con);
?> 

When executed I do get the message "Error: Account could not be created, try again later." 执行后,我确实收到消息“错误:无法创建帐户,请稍后再试。”。 of course. 当然。 - I think I have to change something about the SQL statement but how exactly I am unsure of. -我想我必须对SQL语句进行一些更改,但是我不确定到底有多准确。

mysqli_query is being called twice. mysqli_query被调用两次。 If you call it twice the second time will error because you are trying to give 2 people the same id (Assuming you set your database up correctly). 如果第二次调用两次,则会出错,因为您试图给两个人相同的ID(假设您正确设置了数据库)。

If that doesn't work, I would try replacing mysqli_query with mysqli_multi_query. 如果那不起作用,我将尝试用mysqli_multi_query替换mysqli_query。

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

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