简体   繁体   中英

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. 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) -

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? 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
    $_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.

mysqli_query is being called twice. 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).

If that doesn't work, I would try replacing mysqli_query with mysqli_multi_query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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