Two insert statements in php [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Hi guys how do I have two insert statements in the php codes to store the data into two different tables in the database?
$order = "INSERT INTO NewCase(CaseID, StaffName, Category, PriorityLevel, Status, Date, Summary, ResidentID)
VALUES (NULL, '$staffname', '$category', '$prioritylevel', '$status', '$checkdate', '$summary', NULL)";
$order .= "INSERT INTO NewResident(ResidentID, NRIC, ResidentName, Telephone, Email, Gender, Street1, Street2, PostalCode)
VALUES (NULL, '$nric', '$residentname', '$telephone', NULL, NULL, '$street1', '$street2', '$postalcode')";
$retval = mysqli_multi_query($link, $order);

You should be using mysqli prepared statements and nothing else.
$sql = "INSERT INTO NewCase VALUES (NULL, ?, ?, ?, ?, ?, ?, NULL)";
$stmt = $link->prepare($sql);
$stmt->bind_param("ssssss",$staffname, $category, $prioritylevel, $status, $checkdate, $summary);
$stmt->execute();
$sql = "INSERT INTO NewResident VALUES (NULL, ?,?,?, NULL, NULL, ?,?,?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("ssssss",$nric, $residentname, $telephone, $street1, $street2, $postalcode);
$stmt->execute();

Take a look into transactions may be?
http://php.net/manual/en/mysqli.begin-transaction.php
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
mysqli_query($link, $order1);
mysqli_query($link, $order2);
mysqli_commit($link);
mysqli_close($link);
Also if transaction fail you can always rollback
Also I suggest you use more Object Oriented approach:
$mysqli = new mysqli("localhost", "user", "password", "world");
$mysqli->query();
$mysqli->query();
$mysqli->close();

Related

What's wrong with this SQL INSERT prepared statement? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I'm creating a user registration system for my website. I had this working code:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
$execute = $dbConn->exec($sqlQuery);
However, I found out that this invites the risk of SQL injection. Therefore, I have tried to use a prepared statement to prevent this but I am unable to get it to work. Codes that I've tried:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam($firstname, $surname, $email, 0, $usernameSignup, $passwordHash);
$stmt->execute();
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam("sssss", $firstname, $surname, $email, $usernameSignup, $passwordHash);
$stmt->execute();
// These give the following error: PDOStatement::bindParam() expects at most 5 parameters, 6 given
// So I tried this:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam($firstname, $surname, $email, $usernameSignup, $passwordHash);
$stmt->execute();
// But this throws: PDOStatement::bindParam() expects parameter 3 to be long, string given
I'm not sure why these are throwing the errors given, especially the "expects parameter 3 to be long" as the email field is a string (varchar) data type. Can anyone help with this and explain what is wrong(accountConfirmed is a bit if it helps)?
UPDATE
I realised that I was receiving these errors because I was not using prepared statements and bound parameters in PDO. Thanks to #tadman and #user3783243 in the comment section, I was able to shorten my code by adding my parameters to execute() to do the binding instead of using bindParam() for each of the parameters.
SOLUTION
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->execute(array($firstname, $surname, $email, $usernameSignup, $passwordHash));

Can a prepared statement hold multiple queries in php

I am trying to protect my queries from SQL injections, recently. I have started turning the strings I used to make the queries into statements, however, some of the strings I made need to make multiple queries simultaneously, because one insert's id will be added to the next one as a foreign key, which I'll get by using the LAST_INSERT_ID(), and I need them to be executed one after another because of it.
Can a statement hold multiple queries simultaneously and be executed at once?
Here's what the code was before, by the by.
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES ('{$firstName}', '{$lastName}', '{$phone}', '{$cpf}');";
$sql .= "SELECT LAST_INSERT_ID() INTO #mysql_variable_here;";
$sql .= "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES ('{$email}','{$password}', 1, #mysql_variable_here, '{$created}', {$role}" . $restaurantValue . " );";
$sql .= "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES ('{$number}', '{$street}', '{$city}', '{$stateCode}', '{$zip}', '{$district}', 'BR', '{$created}', #mysql_variable_here);";
$result = $conn->multi_query($sql);```
You can't execute multiple statements in a prepared query:
SQL syntax for prepared statements does not support multi-statements
(that is, multiple statements within a single string separated by ;
characters)
so you will need to prepare and execute each of the queries separately, using mysqli_stmt::insert_id to get the appropriate id value for the second and third queries:
$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`)
VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $firstName, $lastName, $phone, $cpf);
$stmt->execute();
$insert_id = $stmt->insert_id;
$stmt->close();
$sql = "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssiisss', $email, $password, 1, $insert_id, $created, $role, $restaurantValue);
$stmt->execute();
$stmt->close();
$sql = "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$country = 'BR';
$stmt->bind_param('sssssssi', $number, $street, $city, $stateCode, $zip, $district, $country, $created, $insert_id);
$stmt->execute();
$stmt->close();
Note I'm not 100% certain what you're trying to achieve with role_id" . $restaurantInsert . ", you might need to edit the second query appropriately to use that.

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number

I am receiving this error and am unable to figure out why.
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\insert.php on line 32
$SELECT = "SELECT id FROM heroes WHERE name = ? LIMIT 1";
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
//Prepare statement
$stmt = $connection->prepare($SELECT);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0){
$stmt->close();
$stmt = $connection->prepare($INSERT);
$stmt->bind_param("sssss", $name, $title, $bp, $ticket, $diamond);
$stmt->execute();
echo "New hero inserted successfully, sir!";
} else {
echo "There is already a hero with this name, sir!";
}
$stmt->close();
$connection->close();
You don't actually have any params to bind in your insert:
$INSERT = "INSERT INTO heroes (id, name, title, bp, ticket, diamond) VALUES ('NULL', '$name', '$title', '$bp', '$ticket', '$diamond')";
Do this:
$INSERT = "INSERT INTO heroes (name, title, bp, ticket, diamond) VALUES (?, ?, ?, ?, ?)";
Then the values you bind replace the question marks.
Also note there is a very significant difference between NULL and 'NULL' -- the latter is a string. If you have an auto-incrementing ID field, just leave it out of the insert and the database will fill it in for you.

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

MySQL more columns then in php query

I changed to another database with more columns. Nut now my register page doesn't work anymore. The tables all have default settings.
How can I let the query put all the data in the columns and use the defaults for other columns?
This is my query:
mysql_query("
INSERT INTO `users`
(`username`, `password`, `mail`, 'account_created', 'ip_last', 'ip_reg')
VALUES(
'".$naam."', '".$wachtwoord."', '".$email."',
'".$timestamp."', '".$ip."', '".$ip."'
)
");
It worked before, but now on this new database it doesn't work anymore. I didn't change my php version or something.
You can use variables in query strings without quotes.
By the way you should think about more secure -
PDO? What is this magic system
PDO Version:
$query = $db->prepare("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES (?, ?, ?, ?, ?, ?)");
$query->execute(array($naam, $wachtwoord, $email, $timestamp, $ip, $ip));
Trash Version:
mysql_query("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES ($naam, $wachtwoord, $email, $timestamp, $ip, $ip)");
Know the difference between back ticks and single quotes
mysql_query("
INSERT INTO `users` (`username`, `password`, `mail`, `account_created`, `ip_last`, `ip_reg`) VALUES('".$naam."', '".$wachtwoord."', '".$email."', '".$timestamp."', '".$ip."', '".$ip."')");

Categories