php array implode for insert - php

I'm passing an html array to php using jquery serializearray() function.
In php I can access the array using $_POST like
$a = $_POST['htmlarray']
The html array, however, is an array of arrays like so
htmlarray[] = [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]
I want to format the variable $a so that I can insert all the html array values in one single insert query like
INSERT INTO table
(val1, val2, val3, val4, val5, val6)
VALUES
(1,2,3,4,5,6),
(7,8,9,10,11,12),
(13,14,15,16,17,18)
I know I have to use an implode function, can anyone show how this could be done.

I'm not quite sure what an html array is, but try the following:
$a = $_POST['htmlarray'];
// unserialize $a
// build sql query up to '...VALUES '
foreach ($a as $row) {
$sql .= '(';
$sql .= implode(',', $row);
$sql .= ')',
}
This should iterate through the arrays and append all your rows to the string. Note, however, that this code does not take care of SQL Injections at all! Not to be meant for production.

Related

Insert array and non array values to database using a single sql statement

I have this, working, code, for inserting array to database:
$c = array_map(function ($reqNo,$officer,$product,$quantity){return "'$reqNo','$officer','$product','$quantity'";} , $reqNo,$officer,$product,$quantity);
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR) VALUES (".implode('),(', $c).")"))
Now, the problems is that i would like also to insert, alongside the array, none array values to the same database table, using the same sql insert statement..here's my code so far,
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).",'replacement','ICTU','-1','-1','-1',CURDATE(),CURTIME(),'1' )"))
and here's the error i'm getting:
Column count doesn't match value count at row 1
Any ideas on how to go about this?
I did get a way around it, though not sure if it's the correct way..this' how i did it:
//first, i got the length of the array
for($i=0;$i<count($product);$i++){}
//i used array_fill() to duplicate the single values into the length of the array
$new_usage = array_fill(0,$i,$usage);
$new_designation = array_fill(0,$i,$designation);
$QtyA = array_fill(0,$i,"-1");
$QtyA1 = array_fill(0,$i,"-1");
$QtyI = array_fill(0,$i,"-1");
$date = array_fill(0,$i,date("Y-m-d"));
$time = array_fill(0,$i,date("H:i:s"));
$bar = array_fill(0,$i,"1");
//then i put the above new arrays into array_map(), together with the original array
$c = array_map(function ($reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar){return "'$reqNo','$officer','$product','$quantity','$new_usage','$new_designation','$QtyA','$QtyA1','$QtyI','$date','$time','$bar'";} , $reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar);
//from there, i imploded the array_map into the sql insert statement
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).")")){
...
I still don't know if this' the right way to go about it, but all in all, it did work.

How to Use foreach with 2 array variable in php

i have codes like this
<?php
include "assets/config/connect.php";
foreach( $_POST['nim'] as $nim ){
$kode_mk= $_POST['kode_mk'] ;
$nilai= $_POST['nilai'] ;
$tahun_akademik= $_POST['tahun_akademik'] ;
$sql = " INSERT INTO nilai (nim, kode_mk, nilai, tahun_akademik, id_nilai) VALUES ('$nim', '$kode_mk', '$nilai', '$tahun_akademik', NULL) ";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
?>
but the result is not same with my expectation
this is the result
please help me
$kode_mk = $_POST['kode_mk'];
$nilai = $_POST['nilai'];
$tahun_akademik = $_POST['tahun_akademik'];
all variables are arrays, not strings as you expect, you should
var_dump($_POST);
to see the entire structure of POST array
The Error
So assuming kode_mk, nilai, tahun_akademik are all arrays in $_POST you are trying to insert the object of an array as a string. First convert the array to a string using a function like implode().
Solution: Using PHP Implode()
$array = array('hi', 'my', 'name', 'is');
$string = implode(',', $array); // string = 'hi,my,name,is'
Implode works like this implode(glue, array) the glue is a string that is inserted between each element of the array to separate them in a string. You can use explode(delimiter, string) to then reverse the string to an array!
Example Using your code
<?php
include "assets/config/connect.php";
foreach( $_POST['nim'] as $nim ){
$kode_mk= implode(', ', $_POST['kode_mk']);
$nilai= implode(', ', $_POST['nilai']);
$tahun_akademik= implode(', ', $_POST['tahun_akademik']);
$sql = " INSERT INTO nilai (nim, kode_mk, nilai, tahun_akademik, id_nilai) VALUES ('$nim', '$kode_mk', '$nilai', '$tahun_akademik', NULL) ";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
?>
Notes:
Try Using mysqli not the mysql extension for security reasons mentioned by: #messy
Looks like you are looping over $_POST['nim'], but then pulling the same $_POST values for the columns of the database.
We could really use the format and syntax of the $_POST variable
You have to show us what your input data looks like. You can do that with print_r() or var_dump():
print_r($_POST);
From the looks of it, your form inputs are arrays (checkboxes?) and you need to either pull them together into a single string or use each one separately.
Also, there is no reason to continue to gather your POST values inside the loop if there is no change in their values. Pull them up outside the loop.
Finally, the mysql_ extension is deprecated and highly discouraged - you shouldn't be using it to write new code. You also need to validate and sanitize your data before doing any inserts. Easiest way to do the latter is parameterized queries.

Assign POST values to an array in a loop and put array into a database

I have an array containing the names of form input names:
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
The names are identical to the corresponding columns in a database. Instead of using an sql query like so:
$bed_min=$_POST['bed_min'];
$bed_max=$_POST['bed_max'];
$rec_min=$_POST['rec_min'];
$rec_max=$_POST['rec_max'];
$bath_min=$_POST['bath_min'];
$bath_max=$_POST['bath_max'];
$value_min=$_POST['value_min'];
$value_max=$_POST['value_max'];
$query = "UPDATE first_page SET bed_min='$bed_min', bed_max='$bed_max', rec_min='$rec_min', rec_max='$rec_max', bath_min='$bath_min', bath_max='$bath_max', value_min='$value_min', value_max='$value_max', WHERE email_address='$email' ";
Is there a way to automate all this into a smaller lump of code? I know the POST values should not be added to the query diectly, so maybe a loop to assign the POST values to a corresponding array of variables using something like:
foreach ($minmax as $var){
$var = $_POST[$var]
}
(nb i dont think this snippet will work but ive added it because I think with a bit of editing it might!)
After the list of variables have been assigned the POST values, do the update in the $query using two arrays, one with the list of values and one with the list of database columns. Again I dont know how this will work, so pointers would be helpful!
You don't really need the $minmax array of form input names since you can get those from the keys of $_POST.
If the values are all numbers, like they seem to be, then you could do it all in one line like this:
$query = "UPDATE first_page SET " . vsprintf(implode("='%d', ", array_keys($sanitized_POST))."='%d'", array_values($sanitized_POST))." WHERE email_address='$email'";
That's assuming you have already sanitized the items from $_POST into a new array named $sanitized_POST. I know you said in the above comment to ignore sanitization, but I thought I'd add it so you know I'm not suggesting to use the values straight from $_POST.
You could sanitize the $_POST array with something like this:
$sanitized_POST = array_map(function($item) {
return mysqli::real_escape_string($item);
}, $_POST);
Honestly though, you should try to come up with a solution that uses prepared statements.
On a side note, if you have the sanitized post array, then this one line will essentially do what Quixrick has done with variable variables in one of the other answers:
extract($sanitized_POST);
If you assume that all of the values in post have the same names (array keys) as your columns, then something like this could work for you:
$query = "UPDATE first_page SET ";
foreach ($_POST as $key => $var){
$query .= " $key='$var',";
}
$query = rtrim($query,',') . " WHERE email_address='$email' ";
You probably want to use 'Variable Variables' here. Basically, you'd use a double dollar sign $$ to create a variable with the name of the array value.
$_POST['bed_min'] = 'Rick';
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
foreach ($minmax as $var){
$$var = $_POST[$var];
}
print "<BR>BED MIN: ".$bed_min;
This outputs:
BED MIN: Rick

how to construct a mysql query that puts quotes around strings but not numbers?

i have use function for inserting data to my sql.
the data is
function mysql_insert($table, $arr){
if($arr!=''){
$values = array_map('mysql_real_escape_string', array_values($arr));
$keys = array_keys($arr);
$q=('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
//$res = mysql_query($q)OR die(mysql_error());
return $q;
}else{
return false;
}
data and query is came from :
if($crud=='insert'){
$field= array( 'col1' => 'apel',
'c0l2' => 'box1',
'col3' => 200,//integer Quantity
);
$data=mysql_insert('wh',$field);}echo json_encode($data);
and result is
= "INSERT INTO wh (col1,c0l2,col3) VALUES ('apel','box1','200')"
that col3 have value as string. i need that col3 as integer.
what wrong with this code?
In the following code :
implode('\',\'', $values)
the implode is converting the array of values to a string, separating each value by ','
and before and after the implode code, there are also quotes, which will wrap all your values with ' make it look like all the values are strings
but like octern i don't see why the query would fail, even if you are wrapping integer values with ' if the correct data type is selected in the database it should work fine
If you still want to use quates around the string but not around the integer or boolean
try the php function json_encode()
example here: http://codepad.org/Hpvzjnjc
This is happening because the command implode('\',\'', $values) is telling it to turn the array $values into a string, with single quotes and commas between each element. If you want to not put quotes around numbers, you'll need to iterate over $values with a more specific function.
However, it doesn't actually matter. If you give MySQL a string containing a number for a numeric field, it will just convert it to a number of the appropriate type. You can leave it as-is and everything should work.

Insert unknown number of rows into MySQL using PHP

I am trying to insert an unknown number of rows into MySQL using PHP. This is how it should work:
Javascript parses HTML DOM to create a multi-dimensional array based on a css class. The array will have a certain number of rows(or sub-arrays) corresponding to the number of elements that have that class. (This could be any integer 0 or greater... obviously).
Then, on a JavaScript event, the array is sent to a PHP script.
The PHP script will INSERT data from the array into MySQL.
My problem is that I don't know how to tell my PHP script how many values are in the array. And I don't know how to write the mysql_query() without knowing the number of values (or rows) that should be inserted.
You can insert more than one row at a time to MySQL:
INSERT INTO table1 (column1, column2, ...) VALUES (value_col1, value_col2), (value2_col1, value2_col2), ...;
In PHP, you can build your query by looping through rows and adding them to the SQL string:
$sql = "INSERT INTO table1 (col1, col2) VALUES ";
foreach($rows as $i=>$row) {
if ($i>0) {
$sql .= sprintf(",(%s,%s)", $row["col1_value"], $row["col2_value"]);
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
}
mysql_query($sql);
You have to be sure to properly escape your values depending upon what you're actually inserting.
Why don't you prepare a two dimensional array while searching with the css class identifier like this?
//This is jquery code - you can write javascript to do the same
$(`.class`).each(function(i,e){resultsArray.push($(this).val());});
This will save you from the headache of traversing a multidimensional array in the backend and you can simply do a count() in you PHP code and the following query preparation.
Query preparation
Assuming you have a two dimensional array you can use a bulk insert query like this:-
INSERT INTO tablename (a,b)
VALUES
('1', 'one'),
('2', 'two'),
('3', 'three')
And prepare the query dynamically using PHP like this -
$counter = 0;
$valuesPart = NULL;
foreach($_POST as $each)
{
if($counter > 0)
$appendComma = ",";
else
$appendComma ="";
$valuesPart .= $appendComma."(".$each['key1'].",".$each['key2'].")";
$counter++;
}
if(!empty($valuesPart))
$mysql_query = "INSERT INTO tablename (a,b) VALUES ".$valuesPart;
So, you don't need to know how many results are to be actually inserted.
If you stay with the multidimensional array, you will probably need to code or search for a code to traverse the multidimensional array which will probably involve recursion and a lot of complex code. There will be many chances of errors and it will be a slower (may be little but a finite amount which is not necessary).
So I assume the array is getting to PHP successfully, through $_POST or whatever? If you aren't sure then do a var_dump or echo_r so we can see.
EDIT - wow I put explode where I meant implode several times. fixed.
Assuming that it is, and that each 'sub' array is an associative array in form
[0]
'id' => 1
'name' => 'Billy'
'DOB' => .....
[1]
etc.
And the code to build a single query inserting all rows, like this INSERT INTO table ('f1','f2',f3') VALUES ('v11', 'v22', 'v33'), ('v21', 'v22', 'v23'), ......
$escapeAndQuote = function($x) {return "'".mysql_real_escape_string($x)."'";};
$rowwise = function($x) {return '('. implode(', ', array_map($escapeAndQuote, $x)) .')';
$fieldString = $rowwise(array_keys($arr[0]));
$valString = implode(', ', array_map($rowwise, $arr));
$sql = "INSERT INTO table $fieldString VALUES $valString";
mysql_query($sql, $conn);
Use a foreach loop to cycle through the array.
// Example:
foreach($submitted_array as $insert_array)
{
//php and mysql insert query here
}
Perhaps prepared statements would assist you in your endeavors. Essentially you will declare a generic insert statement and then "bind" values to each input. Read more on PHP PDO Prepared Statements.

Categories