Related
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.
I am attempting to send the exact same information to two different tables. I read that this cannot be done with one INSERT query, so I tried doing this.
$stmt2 = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
$stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
if ( false===$stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt2->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$stmt2->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($stmt2->error));
And only the second insert part is working. How can I structure this, so that both INSERT's work?
You are assigning $stmt2 twice - if you have two prepared statements, you need two variables to store them. If you change your code to:
$stmt1 = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
$stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
if ( false===$stmt1 || false===$stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt1->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
$stmt2->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$stmt1->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($stmt1->error));
$stmt2->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($stmt2->error));
it should work.
You can also send both commands in one statement (preferably with named parameters)
$statement = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (:user_id, :firstname, :lastname, :username, :email);
INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (:user_id, :firstname, :lastname, :username, :email);");
$statement->bindValue('user_id', $shuffle_id);
...
The issue I am having is the PHP code below only inserts the data into one table blue. What I want is if the directory category from the POST is equal to for example blue INSERT into Table blue , but if it is equal to yellow INSERT into yellow, but if it's equal to red INSERT into table red.
The only answers I have found deal with insert if exist but not multiple insert if statements. Any help would be greatly appreciated. I am just learning PHP code.
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $_POST['firstname'], $_POST['lastname'], $_POST['city'], $_POST['state'], $_POST['zipcode'], $_POST['directorycategory'], $_POST['active']);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
#oremIpsum1771 Your answer works the best. The final code is as follows
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some directory','password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Connection failed : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$firstname = '$_POST[firstname]';
$lastname = '$_POST[lastname]';
$city = '$_POST[city]';
$state = '$_POST[state]';
$zipcode = '$_POST[zipcode]';
$directorycategory = '$_POST[directorycategory]';
$active = '$_POST[active]';
if($directorycategory == 'Employer'){
$query = ("INSERT INTO employer(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
}
else if($directorycategory == 'Blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Green'){$query = ("INSERT INTO green(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Red'){$query = ("INSERT INTO red(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if($directorycategory == 'Orange'){$query = ("INSERT INTO orange(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
$statement = $mysqli->prepare($query);
//bind parameters
$statement->bind_param('sssssss', $firstname, $lastname, $city, $state, $zipcode, $directorycategory, $active);
if($statement->execute()){
header("some location");
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
I'm not seeing where you have the control structure for the query. If i'm understanding the problem correctly, I would think that you would need something like this:
if(directorycategory == 'blue'){$query = ("INSERT INTO blue(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
else if(directorycategory == 'yellow'){$query = ("INSERT INTO yellow(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)"); }
etc....
$query = ("INSERT INTO ".$_POST['directorycategory']."(
firstname, lastname, city, state, zipcode, directorycategory, active) VALUES(?, ?, ?, ?, ?, ?, ?)");
http://php.net/manual/en/language.operators.string.php
You can use the period to concatenate strings with variables to make 1 big string.
I make code that using pdo to insert information to database and gain XSS protection.
now im few days look at the code and dont see the problem that make the code to not insert the requird information.
Here`s My code:
if ($register = $mysqli->prepare("INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (! $register->execute()) {
echo "אירעה שגיאה";
$register->close();
}else{
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';}
$register->close();
}
And the connection code:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
Thank you.
Use mysqli_affected_rows to get the number of inserted row, if any function fails, check for errors using mysqli_error
$sql = "INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($register = $mysqli->prepare($sql)) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (!$register->execute()) {
echo "אירעה שגיאה";
die("execute() failed: ". mysqli_error($mysqli));
}
if(mysqli_affected_rows($register) > 0){
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';
}else{
echo 'Did not inser any row';
}
}else{
die("prepare() failed: ". mysqli_error($mysqli));
}
When working with the sqlsrv_query command I can request data from the MSSQL server.
This works
But!
When I want to add data it returns the error [error:array].
The code I use for this is:
$tsql= "INSERT INTO dbo.VERLOF_events (id,
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?, ?)";
$var = array('', $username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";
The array values are set in the POST statement.
$afdeling = $row['Afdeling'];
$submit = #$_POST['submit'];
$description = #$_POST["description"];
$evdate = #$_POST["evdate"];
$trdate = #$_POST["trdate"];
$username = #$_SESSION['username'];
$soort = #$_POST['Dagen'];
Why does it return the array error?
I looked it up but could not find the problem returning the error.
Any help is appreciated!
The problem is probably you're trying to add an empty value in the id field. If you set identity on it with auto-numbering, you don't need to include it in your query :
$tsql= "INSERT INTO dbo.VERLOF_events (
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?)";
$var = array($username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";