In a form, multiple Checkbox values to be inserted into database:
My Code:
Array: ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
$a = $_POST['id']; // data from form
$query = "INSERT INTO abc(`x`,`y`,`z`) VALUES " . implode (",","(NULL,$a,'1')");
mysqli_query($dbc,$query);
There seems to be a problem with implode function. How do you concat array using implode?
// Expected output
INSERT INTO abc(`x`,`y`,`z`) VALUES (NULL,1,'1'),(NULL,2,'1'),(NULL,3,'1'),(NULL,4,'1'),
Column y of table abc needs to loop with $a.
If you want to create a batch multiple insertions, first build the batches first, then implode those batches:
$multiple = array_map(function($e) use($dbc) {
$e = $dbc->real_escape_string($e);
return "(NULL, $e, '1')";
}, $a);
$query = "INSERT INTO abc(`x`,`y`,`z`) VALUES " . implode (',', $multiple);
mysqli_query($dbc,$query);
Sidenotes: Its not VALUE, Its VALUES. And remember to use the correct quotes on identifiers. Its supposed to be backticks not single quotes.
INSERT INTO abc('x','y','z') // NOT OK
INSERT INTO abc(`x`,`y`,`z`) // OK
Here you do implode concate.
$query = "INSERT INTO abc('x','y','z') VALUE " . "('" . implode("','", $a) . "')";
Youre using wrong arguments in implode implode() and check your insert query you must use values instead of value
$query = "INSERT INTO abc('x','y','z') VALUES (".implode(",",$a).")";
$a = array(1,2,3,4);
$string = '';
foreach($a as $v){
$string .= "(NULL, $v, 1),";
}
$string = substr($string,0,-1);
$query = "INSERT INTO abc('x','y','z') VALUES $string";
As per your comments in question, This should be your code:
foreach($a as $item)
{
$str[] = "(NULL, '$item', 1)";
}
$query = "INSERT INTO abc(x,y,z) VALUES ".implode(',', $str);
So, you were doing two mistakes:
VALUE should be VALUES
Using implode at wrong place
Related
I wish to create a piece of dynamic SQL where the values from string variables are used as variables in the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'1234');"
This works.
What I need to do however, is to have "variable variables"?
So earlier on in the code:
foreach($array as $val)
{
$s .= ',"$val"[$i]';
}
This creates the string:
s = ,'$val[0]','$val[1]'
When inserted as the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,$s);"
It returns:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'$val[0]','$val[1]');"
Whereas it should return:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'12','34');"
This is being very literal as the MySQL insertion is on a loop where by $val is the array value and [0] is the key.
I'm not sure if this makes sense to anybody as I'm struggling to wrap my head around it, please let me know if my question is to vague or just doesn't make any sense at all.
Thanks
Nick
You are using single quotes, so no string interpolation is done, if you want strings interpolated you have to use double quotes"$var":
$arr = array( 1,2,3);
$i = 0;
echo '$arr[0]'; // prints: $arr[0] <== Your error is here
echo "$arr[0]"; // prints: 1
A better approach
Anyways, you may like to do it this way:
$array = array(12, 34);
$s = implode("', '", $array); // $s is: 12', '34
$s = ", '$s'"; // $s is: '12', '34'
echo $s; // prints: , '12', '34'
From what I could understand from your question, this might help you to achieve what you are looking for.
On your foreach loop you are using
$s .= ',"$val"[$i]';
$val is not concatenated in correct way
try this one
$s .= ','.$val[$i];
You can split values in array by , with implode function
For example:
$array[] = 12;
$array[] = 31;
implode(','$array) returns 12,31
so you could use $s = ','.implode(','$array); to achieve same result
Using your code I think this is what you are trying to do but as I said you are missing attributes.
$s="";
$array = array("12","34");
for($i =0; $i < count($array); $i++)
{
$s .= ",'" . $array[$i] . "'";
}
$sql = "INSERT INTO `product` (`id`,`number`) VALUES (NULL$s);";
I'm exploding a comma separated list into a variable named $tagArray and trying to write those values into incrementing rows of a table.
The code below works in so much as it creates the appropriate number of rows in my table but it only writes the first letter of the comma separating string (ie. if the string reads as "one, two, three", "o" is written in the first row and the remaining two rows have a blank value for column "blog_tag":
$tagInput = $_POST["blog_tags"];
$tagArray = explode(",",$tagInput);
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id)
VALUES ";
$valuesArray = array();
foreach($tagArray as $row){
$tag = mysqli_real_escape_string($conxn, $row['blog_tag']);
$valuesArray[] = "('$tag','$lastID')";
}
$sql_2 .= implode(',', $valuesArray);
if (!mysqli_query($conxn,$sql_2)) {
die('Error: ' . mysqli_error($conxn));
}
This is spaghetti pieced together from various searches here and it's getting close but I can't figure out where it's grabbing just that first letter of the string.
Explode doesn't create associative arrays
$tag = mysqli_real_escape_string($conxn, $row); //instead of $row['blog_tag']
just replace your foreach with this for inserting values of array
foreach($tagArray as $row){
$a=mysqli_real_escape_string($row)
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id) VALUES
('$a','$lastID') ";
}
When I need to loop over something while generating a query from each element, I would use something like
$queryStr = "INSERT INTO tableName (x,y) VALUES ";
for ($i = 0 ; $i < $len ; $i++)
{
$queryStr .= "( ".$thing[$i]['x'].", ".$thing[$i]['b']."), ";
}
//extra code to remove the last comma from string
Would there be an alternative?
I don't mind performance too much (knowing the length of the array is not too big), just something that looks nicer.
Using a prepared statement:
$sql = 'INSERT INTO tableName (x, y) VALUES (:x, :y)';
$sth = $dbh->prepare($sql);
for ($i = 0 ; $i < $len ; $i++)
{
$sth->execute(array(
':x' => $thing[$i]['x'],
':y' => $thing[$i]['b']));
}
More examples: http://www.php.net/manual/en/pdo.prepare.php
A slight improvement to get rid of last part (removing latest comma). You can first create an array of values, then use implode function like:
$queryStr = "INSERT INTO tableName (x,y) VALUES ";
for ($i = 0 ; $i < $len ; $i++)
{
$values[] = "( ".$thing[$i]['x'].", ".$thing[$i]['b'].")";
}
$queryStr .= implode(',', $values);
I like using array_walk and implode for things like this:
$values = array(
array(1, 2, 3),
array(4, 5, 6),
. . .
);
// an array to hold the values to insert
$query = array();
// walk the values and build the query array
array_walk($values, function($v) use(&$query) {
$query[] = "(" . implode(", ", $v) . ")";
});
// dump the output
echo implode(", ", $query);
The result looks like this:
(1, 2, 3), (4, 5, 6), ...
Maybe not much cleaner, but at least it gets rid of the for loop :-)
You could use implode() with array_map():
implode(', ', array_map(function($v) { return '(' . $v['x'] . ', ' . $v['b'] . ')'; }, $things));
Demo
$strCols = '`'.implode('`, `',array_keys($arrValues)).'`'; //Sets the array keys passed in $arrValues up as column names
if ($bolEscape){ //Checks if $bolEscape is true
$arrValues = $this->escape($arrValues); //Calls the escape function
$strValues = '"'.implode('","',array_values($arrValues)).'"'; //Sets the array values passed in $arrValues up as data for the columns
}else{
$strValues = '"'.implode('","',array_values($arrValues)).'"'; //Sets the array values passed in $arrValues up as data for the columns WITHOUT escaping
}
//Creates the SQL statement for the query
$strSQL = 'INSERT INTO `' . $strTable . '` (' . $strCols . ') VALUES (' . $strValues . ')';
Thats part of the database class I have written... I pass in the arrValues ('ColumnName'=>'Value')
I have two arrays, one containing the field names which are imploded into a string called $fields, and one containing the data imploded into $data.
When data is first entered using the INSERT command the query looks like...
mysql_query("UPDATE table ($fields) VALUES ($data)")
(BTW: all data is sanitised)
My goal is to build a mysql UPDATE statement where the syntax is
mysql_query("UPDATE table SET $field1=$data1, $field2=$data2 ...")
and update all fields at once, so I need to combine the two arrays to build the alternating field/data/field/data structure instead of all of the fields followed by all of the data.
My idea is to use array_combine or array_merge and then implode into a string that will then set the function to
mysql_query("UPDATE table SET $imploded-combined-arrays")
I recognise that this won't work as the "glue" of the implode statement has two different values depending upon whether it is equating or separating field/data pairs.
How can I step through both arrays and build a string that is appropriate for the UPDATE syntax?
Thanks,
Cam
Try this
$a = array('key1', 'key2', 'key3');
$b = array('value1', 'value2', 'value3');
$c = array_combine($a, $b);
foreach($c as $key=> $value){
$result[]=$key."='". $value."'";
}
$updatefields= implode (', ', $result);
echo ("update table set " .$updatefields);
OUTPUT
update table set key1='value1', key2='value2', key3='value3'
DEMO
$names = array ('foo', 'bar');
$values = array ('hello', 'world');
$pairs = array ();
foreach ($names as $i => $name)
{
$value = $values [$i];
// $name = mysql_real_escape_string ($name);
// $value = mysql_real_escape_string ($value);
$pairs [] = "`$name` = '$value'";
}
echo ("UPDATE t SET " . implode (', ', $pairs));
For me outputs is:
UPDATE t SET `foo` = 'hello', `bar` = 'world'
I'm trying to save some code with the following. I've an object with variables named the same as table rows so I could create an insert like this one:
$query = "INSERT INTO table ";
$columns = '(';
$values = 'VALUES (';
foreach ($this as $var => $value){
if ($value){
$columns .= $var.', ';
if (!is_int($value))
$value = '\''.$value.'\'';
$values .= $value.', ';
}
}
$columns .= ')';
$values .= ')';
$columns = str_replace (', )', ')', $columns);
$values = str_replace (', )', ')', $values);
$query .= $columns." ".$values;
But every single variable is detected as string and that's not true in all fields as you may imagine.
Does anyone have a solution?
Here's how I would write it:
<?php
$canonical_columns = array_flip(array("column1", "column2", "column3"));
$columns = array_keys(array_intersect_key($canonical_columns, (array) $this));
$params = join(",", array_fill(0, count($columns), "?"));
$columns = join(",", $columns);
$query = "INSERT INTO table ($columns) VALUES ($params)";
$stmt = $pdo->prepare($query);
$stmt->execute(array_values($this));
Stop concatenating fragments of strings to form SQL.
Use PDO, and use parameters for values.
Allowlist column names by comparing inputs to known, valid column names.
It appears as if you numbers are in fact strings. Try to use is_numeric() instead of is_int().
If this ain't enough you can cast the string to an integer and then check for != 0.
You may insert numbers in quotes too, as strings. This will not create an error.