MySQL INSERT with multidimensional php array - php

I'm trying to write an INSERT SQL request to populate a table of my db with a multidimensional array.
The array use the session variables (it's a shopping cart) $_SESSION['panier'], and currently has the following content :
array (size=3)
'ARTCOD' =>
array (size=2)
0 => string 'NA1818BLCFEZ' (length=12)
1 => string 'SER5151BLCFEZ' (length=13)
'COLLIB' =>
array (size=2)
0 => string 'blanc' (length=5)
1 => string 'blanc' (length=5)
'quantite' =>
array (size=2)
0 => int 6
1 => int '8'
My table has more field :
the 'ID' field, which need to auto increment.
the 'reference' field, which contains the reference of the order, I will generate it randomly.
The 'ARTCOD' field, it's the code associated to an article, here it's in $_SESSION['panier']['ARTCOD'].
The 'CLICOD' field, it's the code associated to the client which is ordering, here it's in $_SESSION['CLICOD'].
the 'quantite' field, the quantity of the ordered article, contained in $_SESSION['panier']['quantite'].
The 'type' field, contain the order type, here it's just a defined word that will not change.
And the 'date' field, contain the timestamp of the order.
So I need help to write a function that will generate my MySQL request without using multiple INSERT.
I've already create this:
$query = "";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= 'INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ("", "'.$_SESSION['panier']['ARTCOD']['$i'].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite']['$i'].', "Location", now());';
}
But I prefer something which will give just one INSERT request.
I saw that I need to use the implode function and a foreach loop but I did not manage to create something working.

To combine all those inserts into a single one, you can try this :
$query = "INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= '("", "'.$_SESSION['panier']['ARTCOD'][$i].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite'][$i].', "Location", now()), ';
}
$query = rtrim($query, ', ');
Note : Don't put $i between single quotes.

Related

Multiple INSERT INTO MySQL from $_POST array

I am receiving the following arrays from a form:
array (size=1)
'checkbox' =>
array (size=2)
0 => string '14' (length=2)
1 => string '13' (length=2)
2 => string '15' (length=2)
array (size=1)
'id' => string '1' (length=1)
I need to build a query looking like this:
$sql = "INSERT INTO table(column1,column2) VALUES (14,1),(13,1),(15,1)";
And the first array will be different every time based on the checked checkboxes.
Well, you can try looping with a foreach on that array. So let's say you have named your checkboxes as name="checkbox[]".
Then on the page where you are processing the $_POST vars you can do
$sql = "INSERT INTO table(column1,column2) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
foreach ($_POST['checkbox'] as $box) {
//process each checkbox here
$stmt->bind_param('ss', $box, $otherValue);
$stmt->execute();
}
This is just a pseudo-code to get you started.
You can find more info on prepared statements here: http://php.net/manual/en/mysqli-stmt.bind-param.php
// Create an empty array to store each checkbox value
$values = array();
if(is_array($_POST['checkbox'])){
foreach($_POST['checkbox'] as $checkbox){
foreach($checkbox as $key => $value){
// add each checkbox value to an array
$values[] = ($value,$_POST['id']);
}
}
}
// if the array has values..
if(count($values)){
// implode the values into a string..
$sqlValues = implode(',',$values);
// ..and use that string in the query
$sql = "INSERT INTO table(column1,column2) VALUES $sqlValues";
}

Filter a PHP array so that only unique records remain

I have this PHP array:
array (size=9753)
0 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #13' (length=12)
'total' => string '93.00' (length=5)
1 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #23' (length=12)
'total' => string '77.00' (length=5)
2 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #32' (length=12)
'total' => string '98.00' (length=5)
...
I want to filter it so that only the record with the highest total value remains for every unique brand (there are 100 brands, in total). The result of the operation for this sample should be:
0 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #32' (length=12)
'total' => string '98.00' (length=5)
...
as Brand #1 has the highest total
This is a matter of iterating over the whole array and leaving only one record for each Brand - the one with the highest total.
I've been trying my best, but didn't manage to achieve this. The code that I came up with is this:
$c = count($ordersData);
for($i=1; $i<$c; $i++) {
if($ordersData[$i]['brand'] == $ordersData[$i-1]['brand']
&& $ordersData[$i]['total'] > $ordersData[$i-1]['total']) {
unset($ordersData[$i-1]);
}
}
, but it does not remove all records that should be removed.
Suggestions are much appreciated.
So it seems like your best option is definitely to loop over all the records in $ordersData, as you've done. However, your logic is a bit wacky, and only compares the ordersdata total to the total of the previous order checked.
Instead, you'll likely want to start a new array, and add/overwrite values based on the brand name. Something like this, perhaps:
<?php
$results = array();
foreach($ordersData as $order) {
$brand = $order['brand'];
$total = $order['total'];
// If an order of this brand has already been tracked
if(array_key_exists($brand, $results)) {
// and the total of the current order is greater than what we have recorded
if($results[$brand]['total'] < $total) {
// Then let's replace it!
$results[$brand] = $order;
}
} else {
// Never added this brand before? Add it then
$results[$brand] = $order;
}
}
You can sort the array on total, ascending, then create a temp array indexed on brand (so that the key will get overwritten with later(higher) values), then use array_values to get numerically indexed array:
usort($array, function($a, $b) {
return $b['total'] - $b['total'];
});
$temp=[];
foreach($array as $element) $temp[$element['brand']]=$element;
$out = array_values($temp);
I've also come up with another method. I'm pasting it here just for reference (this is my initial attempt, improved).
$c = count($ordersData);
// Let's iterate through the whole array
for($i=0; $i<$c; $i++) {
// Save the current brand being checked
$currentBrand = $ordersData[$i]['brand'];
// If we can still check against the next record and the this is still the same brand..
if (key_exists($i+1, $ordersData) && $ordersData[$i]['brand'] == $ordersData[$i+1]['brand']) {
// If the next order value for the current brand is higher..
if ( $ordersData[$i]['total'] < $ordersData[$i+1]['total'] ) {
//Let's save/overwrite the higher order for the current brand
$results[$currentBrand] = $ordersData[$i+1];
}
}
}

Converting array to individual variables

I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);

get the values of a form field and save in database

I have a form in which i use two dimensional array for field names.The fields names are below
myform[message][]
myform[name][]
myform[add][]
it means there are three arrays.Every array has arrays inside it.when i var_dump my form after putting values and submitting it.I get the below structure of 2d array.
array
''message'' =>
array
0 => string 'adnan' (length=5)
1 => string 'khan' (length=4)
2 => string 'salman' (length=6)
''name'' =>
array
0 => string 'khan' (length=4)
1 => string 'kamran' (length=6)
2 => string 'khan' (length=4)
''add'' =>
array
0 => string 'asad' (length=4)
1 => string 'khan' (length=4)
2 => string 'abrar' (length=5)
As you can see the associative array.I want to store the values of message,name and add in a database table having three fields to store the values of message,name and add fields in a single query by using some loop like foreach.
when i use this code
foreach($_REQUEST['myform'] as $val)
foreach($val as $v)
{
echo $v;
}
I get all the values of the array.But i think i am unable to save it to database table
as all the values are in the variable $v.How to store message in a message field,name in name field and add in an add field in a table of a db.
please advice.Thanks
The looping is the easy part.
if (isset($_REQUEST['myform']))
{
foreach($_REQUEST['myform'] as $key=>$value)
{
// DO SOMETHING
}
}
The hard part is knowing what you want to do. You say put it in a database but you don't give any real info about what or where. Just make sure you carefully escape any user input before storing it, or better yet use prepared queries.

How to merge my arrays for DB insertion?

I have 2 associative arrays.
Array ( [title1] => test1 [title2] => test2 [title3] => test3 )
and
Array ( [image1] => images1.jpeg [image2] => images2.jpg [image3] => images3.png )
I want to insert each title and image name into database columns(image title and image name).
How it is possible? Anyway to merge them and after that do insertion?
$finalArray = array();
// Use min to avoid improper "OutOfBounds"
$lengthOfArray = min(count($array1), count($array2));
for(i = 1; i <= $lengthOfArray; $i++) {
array_push($finalArray,
array(
'title' => $array1['title' + $i],
'image' => $array2['image' + $i]
)
);
}
With this, in your finalArray you will have tuples of title an image for every database entry.
Look at array_combine()
Maybe instead of combining the arrays, you can use a foreach to construct your query from the two arrays:
//ARRAYS
$a1=array('title1' => 'test1','title2' => 'test2','title3' => 'test3',);
$a2=array('image1' => 'images1.jpeg', 'image2' => 'images2.jpg', 'image3' => 'images3.png');
$fos=''; //we will collect values into this string
foreach ($a1 as $k=>$v) { //we iterate through the first array
$k2=substr($k, 5); //we get the number from the array key (like 2 from title2)
$fos.=empty($fos) ? '' : ', '; //adding commas when needed
$fos.="('{$v}', '{$a2['image'.$k2]}')"; //adding the right values to the values string
}
$q="insert into images (title, filename) values $fos"; //and finishing up the query
In this case the constructed query will be like:
insert into images (title, filename) values
('test1', 'images1.jpeg'),
('test2', 'images2.jpg'),
('test3', 'images3.png')
Note: of course array values need to be correctly escaped for DB usage
array_merge($array1, $array2);

Categories