I am trying to do multiple insertions using mysqli_multi_query() and following is my code. The issue is its not executing the result . Kindly let me know what i did wrong?
$query = "INSERT INTO crap_table (name, number, class)VALUES ('Peter', 35,'BS')";
$query .= "INSERT INTO crap_table (name, number, class)VALUES ('Sahil', 35,'MS')";
mysqli_multi_query($con,$query);
mysqli_multi_query
Executes one or multiple queries which are concatenated by a semicolon.
You need to have a ; between them. Like
$query = "INSERT INTO crap_table (name, number, class)VALUES ('Peter', 35,'BS');";
^
$query .= "INSERT INTO crap_table (name, number, class)VALUES ('Sahil', 35,'MS')";
Provided that you are connected to the database already? Like
$con= mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "INSERT INTO crap_table (name, number, class)VALUES ('Peter', 35,'BS');";
$query .= "INSERT INTO crap_table (name, number, class)VALUES ('Sahil', 35,'MS')";
mysqli_multi_query($con,$query);
You forgot ; between your queries.
Executes one or multiple queries which are concatenated by a
semicolon.
Related
This question already has answers here:
Multiple mysql INSERT statements in one query php [duplicate]
(8 answers)
Closed 3 years ago.
I'm trying to insert multiple data in one table, however I got an error that says:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf')INSERT INT' at line 1
Here's the method:
$sql = "INSERT INTO author (firstname, lastname) VALUES ('Roal', 'Dahl')";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf')";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Jane', 'Doe')";
Do I need to create a for loop for this? How could this work?
You can do this :
$sql = INSERT INTO author ( firstname, lastname) VALUES ('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe');
Generally, mysqli and PDO cannot execute multiple statements in a single query. There are alternatives like mysqli_multi_query, but that is not really what you need.
Your query can have multiple rows added by appending extra sections after VALUES like so:
$sql = "INSERT INTO author (firstname, lastname) VALUES ";
$sql .= "('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe')";
You can use two options:
mysqli_multi_query
$sql = "INSERT INTO author (firstname, lastname) VALUES ('Roal', 'Dahl');";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf');";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Jane', 'Doe');";
if(!$mysqli->multi_query($sql)){
echo 'Error query:'. $mysqli->error . '.';
}else{
//do any operation
}
Or use one query like:
$sql = INSERT INTO author ( firstname, lastname) VALUES ('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe');
if(!$mysqli->query($sql)){
echo 'Error query:'. $mysqli->error . '.';
}else{
//do any operation
}
Change $mysqli with your connection
I have to insert 2 queries and I want run them with multi_queries. In every run of the file there should be 2 row added to the table but my problem is that they don't get inserted. My connection to the db is ok and I tested the queries with that
$q1 ="INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('123456789','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42')";
$q1 .="INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('987654321','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42')";
$result = $conn->multi_query( $q1 );
try array to store data. then take the count of the array and run the loop depend on array count. execute the query inside the loop. give me full detail i ll explain clearly. thnank you
If you are inserting into a single table, you can write your query like this
$query = "INSERT INTO auto_charge(phone,charged_at,created_at,updated_at)
VALUES
('123456789','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42'),
('987654321','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42');";
$result = $conn->query($query )
Or, if you are inserting into multiple tables, you can write like this
$sql = "INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('123456789','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42');";
$sql .= "INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('987654321','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42');";
$result = $conn->multi_query($sql)
Note: Each SQL statement must be separated by a semicolon.
Your syntax is wrong you can insert multiple values within single insert query like the code below
Insert into TableName(Column1Name, Column2Name) Values
(Value1, Value2),
(Value3, Value4),
and so on... ;
I hope this will help you.
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "dbname");
$query ="INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('123456789','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42')";
$query .="INSERT INTO auto_charge(phone,charged_at,created_at,updated_at) VALUES ('987654321','2018-01-24 12:37:07','2018-01-27 09:19:42','2018-01-27 09:19:42')";
/* execute multi query */
mysqli_multi_query($link, $query);
?>
Try This.
I have the follow php script for registering a user
<?php
require_once "setting.php";
extract($_REQUEST);
$link = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if (mysqli_connect_errno()){
echo "Connection failed".mysqli_connect_error();
}
$initQuery = "SELECT * FROM users WHERE email = ".$email;
$initResult = mysqli_query($link, $initQuery);
$dbResults = mysqli_fetch_array($initResult, MYSQLI_ASSOC);
if($dbResults == null ){
echo('in the if statement');
$userId = uniqid();
echo($userId);
$query = "INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId )";
echo($query);
$addResult = mysqli_query($link, $query);
echo($addResult);
}
mysqli_free_result($initResult);
mysqli_free_result($addResult);
mysqli_close($link);
?>
The second mysqli_query is not adding a user, I've checked the syntax of the sql statement and it works fine. Does anyone have any ideas?
Also I was thinking about maybe trying to write a mysqli_multi_query to run both queries. I've read that the multi_query will return false if the first query fails, is there anyway to have it execute the second query if the first one fails and not execute the second query if the first one succeeds?
For the love of God, at least put the string values inside quotes if not use prepared statements
"INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId)"
Is invalid. Those string values should be inside quotes
"INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId')"
Please read this before you implement the solution given above:
How can I prevent SQL injection in PHP?
At the very least, please escape the values with mysqli_real_escape_string
Use quotes for your values.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
$addResult = mysqli_query($link, $query);
If you are facing error than use die function to get the error detail.
$addResult = mysqli_query($link, $query) or die(mysqli_error($link));
It will show you the error also.
Hope this works:
$query = "INSERT INTO users (email, password, userId) VALUES ('$email', '$password', $userId)";
Give a space after table name and all the variables in single quote. :)
UPDATE
Space is not mandatory to give, but would be good for better coding :)
Try to put the values inside quotes.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
To understand why quotes are mandatory i give an example :).
Mysql supports SELECT from another table for inserted values like in the code below:
INSERT INTO users (email, password, userId)
VALUES
((SELECT email FROM user_info WHERE id = '$userId'),'$password','$userId'))
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
Okay, so I'm updating my site from MySQL to MySQLi, which means I have to re-code some of the database stuff.
I looked on php.net on how to use MySQLi queries to insert data into a table and did exactly what they said to, but no luck.
Here's my connection variable:
$con = mysqli_connect("localhost", "username", "password", "database");
And here is the code to insert the data:
mysqli_query($con, "INSERT INTO users ('user', 'pass', 'email') VALUES ('$user', '$pass', '$email')");
It doesn't reply with any errors, and it just takes me to the intended landing page. It doesn't actually add the data to the table though.
Any ideas?
As answered above, removing the quotes from the column names will solve your problem:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
But I also noted that your script is vulnerable against SQL injection attacks.
In MySQLi you can prepare your statements before execution, so you will be sure that no one will inject SQL commands in your database.
If you don't want to prepare each sql statements before execution, at least use the mysqli_real_escape_string function, that will protect your system against SQL injection too. Use like that:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('" . mysqli_real_escape_string($user) . "', '" . mysqli_real_escape_string($pass) . "', '" . mysqli_real_escape_string($email) . "')");
remove single quotes from column names
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
OR
mysqli_query($con, "INSERT INTO users (`user`, `pass`, `email`) VALUES ('$user', '$pass', '$email')");