How to insert multiple values in a single query - php

Please somebody help me. In below code the query will execute 3 times , means query execution will depend on number of elements in array.
Please guide me how to run this query with inserting all data at once
$products = array("shirt" , "paint" , "socks");
$price = array("200" , "600" , "50");
$quantity = array("3" , "2" , "2");
$num = 0; while($num <= count($products))
{
$mysqli->query("insert into new_order set
product = '".$products[$num]."' ,
price = '".$price[$num]."' ,
quantity = '".$quantity[$num]."'
");
$num++;
}

It won't throw any error untill you'll be getting same number of values within an array
$counts = count($products);
$query = "insert into new_order (product,price,quantity) values ";
foreach($products as $key => $value){
$query .= "('$value','$price[$key]','$quantity[$key]')";
$query .= (++$key == $counts) ? '' : ',';
}
$mysqli->query($query);
Query looks like:
//insert into new_order (product,price,quantity) values('shirt','200','3'),('paint','600','2'),('socks','50','2')

Iterate over each item in $products to build $sql string:
$sql = "insert into new_order(product, price, quantity) values ";
for($i=0;$i<count($products);$i++){
$sql .= "({$products[$i]}, {$price[$i]}, {$quantity[$i]}),";
}
$sql = substr($sql,0,-1); //cut off the trailing comma
$mysqli->query($sql);
// insert into new_order(product, price, quantity) values (shirt, 200, 3),(paint, 600, 2),(socks, 50, 2)

Related

Writing to database using foreach

I have Three arrays and i want to write them to database , The issue I face is whenever the values are written to the particular column the rest of the column is left empty.
The
$name_array = array(3) { [0]"Name1" [1]=>"Name2" [2]=> "Name3" }
$roll_array = array(3) { [0]=>"1" [1]=>"2" [2]=>"3" }
$att_array = array(3) { [0]=>"Present" [1]=>"Present" [2]=>"absent" }
I have three columns in DB "NAME" "ROLL" "ATTENDANCE"
I want to store all the array data to the database at the same time.
so it should look like this
NAME ROLL ATTENDANCE
Name1 1 present
Name2 2 present
Name3 3 absent
Here is the code i tried but it just add each values to the column and leaves the other column empty. So the first three rows has only ROLLNO and next three row has only NAME and last three rows has only ATTENDANCE.
$name_values = array();
$roll_values = array();
$att_values = array();
foreach ($name_array as $key => $name_values) {
$name_values = mysqli_real_escape_string($connection,$name_values);
$sql= "INSERT INTO `aclass12` (Name) VALUES ('$name_values')";
mysqli_query($connection,$sql);
}
foreach ($roll_array as $key => $roll_values) {
$roll_values = mysqli_real_escape_string($connection,$roll_values);
$sql= "INSERT INTO `aclass12` (RollNo) VALUES ('$roll_values')";
}
foreach ($att_array as $key => $att_values) {
$att_values = mysqli_real_escape_string($connection,$att_values);
$sql= "INSERT INTO `aclass12` (attendance) VALUES ('$att_values')";
}
I know this is not the right way to do . and whats the way to do this ?
Simply use one array as the master, and the key of that array to access the other 2 arrays data.
Then insert all the data in a single INSERT
Its also a good idea to check that the INSERT actually worked, so I added a little bit of error checking
foreach ($name_array as $key => $value) {
$name = mysqli_real_escape_string($connection,$value);
$roll = mysqli_real_escape_string($connection,$roll_values[$key]);
$att = mysqli_real_escape_string($connection,$att_array[$key]);
$sql = "INSERT INTO `aclass12`
(Name, RollNo, attendance)
VALUES ('$value', '$roll', '$att')";
$res = mysqli_query($connection,$sql);
if ( $res === FALSE ) {
echo mysqli_error();
exit;
}
}
Use only one foreach and access the elements of the arrays there. Like this:
foreach ($name_array as $key => $name_values) {
$name_values = mysqli_real_escape_string($connection,$name_values);
$roll_values = mysqli_real_escape_string($connection,$roll_array[$key]);
$att_values = mysqli_real_escape_string($connection,$att_array[$key]);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name_values', '$roll_values', '$att_values')";
mysqli_query($connection,$sql);
}
Also, it's recommended to use prepared statements, because they prevent SQL njection attacks. More information here.
Try it this ways
for($i = 0; $i < count($name_array);$i++) {
$name_values = mysqli_real_escape_string($connection,$name_array[$i]);
$roll_values = mysqli_real_escape_string($connection,$roll_array[$i]);
$att_values = mysqli_real_escape_string($connection,$att_array[$i]);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name_values', '$roll_values','$att_values')";
}
Other option is to use multidimensional array with foreach.
foreach($name_array as $n_k=>$name) {
$roll = (isset($roll_array[$n_k])) ? $roll_array[$n_k] : '';
$att = (isset($att_array[$n_k])) ? $att_array[$n_k] : '';
$name = mysqli_real_escape_string($connection,$name);
$roll = mysqli_real_escape_string($connection,$roll);
$att = mysqli_real_escape_string($connection,$att);
$sql= "INSERT INTO `aclass12` (Name, RollNo, attendance) VALUES ('$name','$roll','$att')";
mysqli_query($connection,$sql);
}
I do think it would be best to use since mysql query to inject it and simply concatenate everything before that. That's something like this:
$query = "INSERT INTO tbl_name (col1, col2, col3) VALUES ";
for ($i = 0; $i < count($name_array); $i++) {
$name = mysqli_real_escape_string($conn, $name_array[$i]);
$roll = mysqli_real_escape_string($conn, $roll_array[$i]);
$att = mysqli_real_escape_string($conn, $att_array[$i]);
$query .= "('{$name}', '{$roll}', '{$att}'),";
}
$query = trim($query, ',');
$query = $query . ';';
mysqli_query($connection,$sql);
Add some damage control there (check for errors) and that's it.

PHP Insert multiple rows in split batches

I have a query to insert multiple rows in split batches. Basically, I need to split inserts in batches so that I can generate a unique random ID to the inserted batch.
What I've tried and failed with many different options, one of them as follow.
$batch = 150;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++){
$columns1 = $results[$i]['column'];
if($i==$batch){
$randd = randcode(5).time();
$sql = "INSERT INTO `newtable` SET `columns1` = ".$con->qstr($columns1).", `rcode` = ".$con->qstr($randd).", `DATE_PUBLISHED` = ".$con->qstr($sdate);
$results=$con->Execute($sql);
$i=0;
}
}
However, am not successful in inserting unique code to every 150 batch inserted query.
Where am I going wrong in generating random unique code for every batch? And also I would like to know if there is less than 150 records, then how to handle the same?
This will provide you with the logic for a basic way for setting a random ID per batch.
In this example, there is no database connectivity. You will have to add that yourself. You also want to have a look at the syntax for the INSERT statement (spoiler: INSERT INTO <table name> (<columns>) VALUES (<values>)).
// For this example, generate a result array with 350 rows
// (remove when using actual db query)
for ($i = 1; $i <= 350; $i++) {
$results[] = ['column' => 'column ' . $i];
}
// Loop through all result rows
foreach ($results as $batchCounter => $result) {
if ($batchCounter % 150 == 0) {
// Generate a new random ID for the first row and every 150 rows
$random = uniqid();
}
// Replace with proper insert statement
echo "Insert random ", $random, ' for column "', $result['column'], '"', PHP_EOL;
}
Output:
Insert random 55e0186b0607f for column "column 1"
Insert random 55e0186b0607f for column "column 2"
Insert random 55e0186b0607f for column "column 3"
...
Insert random 55e0186b0607f for column "column 150"
Insert random 55e0186b063da for column "column 151"
Insert random 55e0186b063da for column "column 152"
Insert random 55e0186b063da for column "column 153"
...
Insert random 55e0186b063da for column "column 300"
Insert random 55e0186b0666e for column "column 301"
Insert random 55e0186b0666e for column "column 302"
Insert random 55e0186b0666e for column "column 303"
...
Insert random 55e0186b0666e for column "column 350"
You have to try this one
<?php
$batch = 0;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
$sql = "";
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==0)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
if($batch==150)
{
$results=$con->Execute($sql);
$batch=0;
$sql="";
}
$batch++;
}
You have to try this one. I fixed some errors from your code to insert records successfully:
<?php
$batch = 1;
$rows = 0;
$sql = "";
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==1)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
$rows++;
if($batch==100)
{
$this->SendRecords($conn, $sql);
$batch=1;
$sql="";
} else if($rows == count($results) && $batch > 1 && $batch<=100){
$this->SendRecords($conn, $sql);
$batch=0;
$sql="";
}else {
$batch++;
$sql.=",";
}
}

Php insert/update multple row, using array and not a foreach

I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.
I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$sql = "update ppl set firstname = $b, lastname = $c where id = $a";
The same can be said for an insert.
$sql = "insert into ppl (firstname,lastname) value ($b,$c)";
The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.
Thanks in advance.
if (count($a) <= 0)
return; // nothing to do
$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
$id = array_shift($a);
$fname = array_shift($b);
$lname = array_shift($c);
$sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma
$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";
//run your sql
this will allow you to run all of them at once.
For update you can do as follows
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$i=0;
foreach($b as $fname){
if( !empty($b[$i]))
{
$sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
}
$i++;
}
and for insert you can try
$i=0;
$var = '';
foreach($b as $fname){
if( !empty($b[$i]))
{
$var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
}
$i++;
}
if(!empty($var)){
$sql = "insert into ppl(id,firstname,lastname) values ".$var;
}

How to deal with SELECT(MAX()) in mysql inside a foreach using PHP and Codeigniter

I'm using SELECT(MAX()) inside a foreach loop and this is my code:
foreach($_POST['image_Basename'] as $key=>$image_Basename){
$image_Title = $this->input->post('image_Title');
$image_Category_Id = $this->input->post('image_Category_Id');
$this->db->query("INSERT INTO mg_gallery (image_Group_Id, image_title, image_Basename, image_Category_Id)
SELECT 1 + coalesce((SELECT max(image_Group_Id) FROM mg_gallery), 0), '$image_Title', '$image_Basename', '$image_Category_Id'
");
}
The problem is that for each image_Basename, query produces a new number.
For example, if I got 3 image_Basenames, it will insert 1, 2 and 3 for those three image_Basenames. But I want it to insert the same number to all of image_Basenames.
For example, if the max number in the image_Group_Id is 1, then add number 2 for each image_Basename. How can I do that?! I've put
SELECT 1 + coalesce((SELECT max(image_Group_Id) FROM mg_gallery
outside of the foreach loop, but it didn't work!!!
The answer is added below by myself
EDITED 2
Try this if it works or not,
$maxRs = $this->db->query('SELECT max(image_Group_Id) AS max FROM mg_gallery');
echo $this->db->last_query();die; #run this query in your phpmyadmin and debug it.
if($maxRs->num_rows() > 0){
$maxData = $maxRs->row_array();
echo "here :".$maxID = $maxData['max'];die;
}else{
$maxID = 0;
}
//echo "max : ".$maxID;die; #check if its returning the corrent maxid or not.
foreach($_POST['image_Basename'] as $key=>$image_Basename){
$image_Title = $this->input->post('image_Title');
$image_Category_Id = $this->input->post('image_Category_Id');
$this->db->query("INSERT INTO mg_gallery (image_Group_Id, image_title, image_Basename, image_Category_Id)
$maxID, '$image_Title', '$image_Basename', '$image_Category_Id'
");
echo $this->db->last_query();die; #check the query its generating is correct or not and run directly at phpmyadmin
}
I'm not fully sure what kind of data you have and exactly what you want, but I'll help you towards the right direction:
$int_basename = (int)max($this->input->post('image_Basename'));
$str_image_title = $this->input->post('image_Title');
$str_image_category_id = $this->input->post('image_Category_Id');
$query = $this->db->query("SELECT max(image_Group_Id) AS max FROM mg_gallery");
$int_max = (int)$query->row()->max;
$arr_union = array();
for($i = 1; $i <= 3; $i++)
if ($i == 1)
$arr_union = "SELECT " . ($int_max + $i) . " AS id";
else $arr_union = "SELECT " . ($int_max + $i);
$str_union = implode(' UNION ', $arr_union);
$this->db->query("
INSERT INTO mg_gallery (image_Group_Id, image_title, image_Basename, image_Category_Id)
SELECT h.id, ?, ?, ?
FROM ({$str_union}) AS h
", array($str_image_title, $int_basename, $str_image_category_id));
This would only run the query twice and spare your database the trouble of loop queries. I also escaped the values through $this->db->query() as intended to avoid mysql injections. This doesn't really require INSERT ... SELECT as INSERT ... VALUES is enough.
First of all, you should never be inserting values directly from the POST array. But in the interest of just addressing the question at hand, I'll leave the code as is.
You need to query for the MAX(image_Group_Id) before starting the loop and not do a + 1 inside the loop. Like this:
$get_group_id = $this->db->query("SELECT 1 + coalesce((SELECT max(image_Group_Id) AS group_id FROM mg_gallery), 0)");
$get_group_id_array = $get_group_id->fetch_assoc();
$group_id = $get_group_id_array['group_id'];
foreach($_POST['image_Basename'] as $key=>$image_Basename){
$image_Title = $this->input->post('image_Title');
$image_Category_Id = $this->input->post('image_Category_Id');
$this->db->query("INSERT INTO mg_gallery (image_Group_Id, image_title, image_Basename, image_Category_Id)
$group_id, '$image_Title', '$image_Basename', '$image_Category_Id'
");
}
IT WORKS:
Specially thanks to Niloy Saha, finally, I got the answer, and this is the code I've used:
$getMaxValue = $this->db->query('SELECT 1 + coalesce((SELECT MAX(image_Group_Id)), 0) AS image_Group_Id FROM mg_gallery');
if($getMaxValue->num_rows() > 0){
$group_Id = $getMaxValue->row_array();
$image_Group_Id = $group_Id['image_Group_Id'];
}else{
$image_Group_Id = 0;
}
foreach($_POST['image_Basename'] as $key=>$image_Basename){
$image_Title = $this->input->post('image_Title');
$image_Category_Id = $this->input->post('image_Category_Id');
$this->db->query("INSERT INTO mg_gallery (image_title, image_Basename, image_Category_Id, image_Group_Id)
VALUES ('$image_Title', '$image_Basename', '$image_Category_Id', $image_Group_Id)
");
}

php - mssql_fetch_array

I am trying to update an MSSQL database through PHP, as shown in in the following code. The problem is that the first 5 lines of code are successfully being executed but the program is not entering in the while loop. I am sure that the array $items contains records.
function updateOrder($items, $cardNo){
if($items){
$orderid = generateGuid();
$username = $_SESSION['username'];
$query = "INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount, OrderVatRate, CustomerUsername) ";
$query .= " VALUES ('".mssql_guid_string($orderid)."',".date('Y-m-d').", 'PE', '$cardNo', 0, 0.18, '$username')";
$result = mssql_query($query) or die("Unable to place order"/*mssql_get_last_message()*/);
while($row = mssql_fetch_array( $items )){
$tmpId = generateGuid();
$tmpPrice = getUserPrice($username, $row["ProductId"]);
$query = "INSERT INTO Orders_Details (OrderDetailsId, ProductPrice, Qty, OrderId, ProductId)";
$query .= "VALUES ('".mssql_guid_string($tmpId)."', $tmpPrice, '".$row["Qty"]."', '".mssql_guid_string($orderid)."', 0, 0.18, '".$row["ProductId"]."')";
echo($query);
$result = mssql_query($query) or die("Unable to place order"/*mssql_get_last_message()*/);
}
}
}
mssql_fetch_array takes a parameter that is the return of a mssql_query : http://php.net/manual/en/function.mssql-fetch-array.php. What is $items?
Something worng with $items in while($row = mssql_fetch_array( $items )) either it's having no value or you are sending wrong in $items
If items having any value like items id then run a select query for selecting items having id in $items and use return of mssql_query in mssql_fetch_array
could it be that the date should be escaped?
Code:
$query = "INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount, OrderVatRate, CustomerUsername) ";
$query .= " VALUES ('".mssql_guid_string($orderid)."',".date('Y-m-d').", 'PE', '$cardNo', 0, 0.18, '$username')";
$query may look like:
INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount,
OrderVatRate, CustomerUsername)
VALUES ('100',2012-1-20,'PE','10', 0, 0.18, 'username')
I solved the problem by separating the 2 UPDATE actions into two different methods and call the method that populates $items twice.
The last query before while($row = mssql_fetch_array( $items )) is an INSERT, so mssql_fetch_array() will never fetch anything!

Categories