insert multiple row to db in same time with multi_query - php

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.

Related

How to insert the same record into the database a number of times?

I have a numeric PHP variable named $quantity and based on the number set in this variable, I want to insert the same record in the MySQL table.
Example:
$quantity = '4';
$sql1 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql2 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql3 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql4 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
You can achieve this by using a loop and a prepared statement. You need to execute the same statement multiple times. This is also very useful if the values are dynamic and they could change, e.g. the values are coming from user input.
Prerequisite:
You need to open a connection to your database. If you use MySQL then the connection would look something like this:
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Now you can prepare a statement which we will execute in a loop multiple times.
$stmt = $pdo->prepare("INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());");
You can use any loop you like but for a simple scenario where we want the same code to be executed a number of times, a while loop is sufficient.
$quantity = 4;
while ($quantity--) {
$stmt->execute();
}
If it is easier for you, you can use for loop, too.
for($quantity = 0; $quantity < 4; $quantity++) {
$stmt->execute();
}
Try something like this:
// NOTICE - Make sure you are escaping any end-user supplied values correctly - See PHP docs for examples of how
$sql_template = 'INSERT INTO `table_quantity` (`username`, `code`, `quantity`, `data`) VALUES (\'John\', \'34438\', \'1\', now());';
$quantity = 5;
$sql = '';
foreach (range(1, $quantity) as $i) {
$sql .= $sql_template;
}
echo $sql;
See the following docs for explanations:
foreach
range()
append to string
Escape SQL values with PDO
Escape SQL values with MySQLi

PHP - date(time) insert into DB

I'm using a time method:
$time= date('h:i:s');
What I want is to put this time into database in mySQL,
I used:
$query = mysqli_query($conn, "INSERT INTO tab ('ltime') VALUES ($time)"); but it's not working
Where tab is a table and a ltime is a Column with time Type.
What am I doing wrong?
Regards
Your query will goes like this.
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ('$time')");
Your query should be like this
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
Columns and tables should have backticks and not single quotes
INSERT INTO `tab` (`ltime`) VALUES ($time)
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
Don't use '' when assigning the column name
The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)VALUES (value1, value2, value3, ...);
If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query
INSERT INTO table_name VALUES (value1, value2, value3, ...);
In your case:
$query = mysqli_query($conn, "INSERT INTO tab (ltime) VALUES ($time)");
there is no need to single quote with column name:
Reference: https://www.w3schools.com/sql/sql_insert.asp

second mysqli_query not working

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

How to insert multiple rows by mysqli_multi_query()?

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.

Insert items in a table using a for loop

I've deleted an old, badly worded question and am reposting to not waste anyone's time.
I'm trying to query stuff from two tables, rooms and items. Then in a nested loop, create an entry in a 3rd table using info from the first two.
'For each room, insert ALL the standard items'
<?php
mysql_connect("******", "****", "******") or die(mysql_error());
mysql_select_db("MaintenanceTracking") or die(mysql_error());// Check connection
//collect standard items names
$stditemdata = 'SELECT * FROM `StandardItems`';
$itemresult = mysql_query($stditemdata) or die("Couldn't execute query. ". mysql_error());
$itemarray = mysql_fetch_array( $itemresult ));
//collect room info
$roomdata = 'SELECT * FROM `Rooms`';
$roomresult = mysql_query($roomdata) or die("Couldn't execute query. ". mysql_error());
//repeat for each room
while($room = mysql_fetch_array( $roomresult ))
{
//repeat for each item
for ($i = 0; $i <= count($itemarray); $i++)
{
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
}
}
?>
I'm pretty new to php and must appologize that the syntax sometimes gets me stumped...I notoriously miss the semi-colon at the ends of rows, for example.
A million thanks in advance to anyone and everyone who can help me out.
kindest regards
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
It should be
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
You use mysqlquery instead of mysql_query
To avoid duplication of mysql-reserved names (f.e. date, table etc) use this syntax
`column_name` or `table_name`
UPDATE
oh.. i miss! look, you try to write some strings into DB here
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
All strings in queries must be concluded in quotes single ' or double ", so your query should looks like
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, \"$itemarray['Name']\", \"$room['LocationCode']\")");
(i use \ symbol before " to escape quote), but i suggest you to use syntaxys like this:
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, '".$itemarray['Name']."', '".$room['LocationCode']."')");

Categories