How to 'really' detect integers from DB? - php

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.

Related

What is the purpose of strlen($query)-2;

I got this code from google and it fulfills my requirement, but I don't understand the meaning of this line:
substr($query,0,strlen($query)-2)
Could somebody explain it to me?
<?php
function insert($tablename, $parameter_order, $values)
{
$query = "insert into $tablename (";
foreach($parameter_order as $po)
{
$query .= $po.', ';
}
$query = substr($query,0,strlen($query)-2).') values (';
foreach($values as $v)
{
$query .= "'$v', ";
}
$query = substr($query,0,strlen($query)-2).');';
return $this->makeQuery($query);
}
?>
This is what those functions do exactly:
substr() is used to generate a sub-string of specified length from another string.
strlen() will return the length of the provided string.
Code substr($query,0,strlen($query)-2) removes comma and space from foreach Loop.
The line removes the last comma and space from $query. These characters have been added in the foreach loop to glue together the elements of $parameter_order.
Note that this standard task is usually done better with the implode() function:
$query = "insert into $tablename (" . implode (', ', $parameter_order) . ' ) values (';

Joining array values into string in MySQL multiple insert

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

More elegant way in PHP to generate a query from array elements

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

PHP -> PDO Update Function using Foreach array merge

The following code is supposed to check for the column names of a table. Then check to see if a corresponding variable has been $_POST and if it has add it to the $SQL. I believe there is a problem with the array that contains a series of arrays but I don't know how to dix it.
$where = $_POST['where'];
$is = $_POST['is'];
$table = $_POST['table'];
$sql = "UPDATE $table SET";
$array = array();
$columnnames = columnnames('blog');
foreach ($columnnames as $columnname){
if($_POST[$columnname]){
$sql .= " $columnname = :$columnname,";
$array .= array(':$columnname' => $_POST[$columnname],);
}
}
$sql = rtrim($sql,',');
$array = rtrim($array,',');
$sql .= " WHERE $where = '$is'";
$q = $rikdb->prepare($sql);
$q->execute($array);
For the sake of comprehension please except that $columnnames = columnnames('blog'); works as it does.
Change this:
$array .= array(':$columnname' => $_POST[$columnname],);
to this:
$array[':$columnname'] = $_POST[$columnname];
and after that use rtrim only on $sql.
the problem is here $array .= array(':$columnname' => $_POST[$columnname],);
you have a , part of the value which is not literal. change it to be like
$array .= array(':$columnname' => $_POST[$columnname] . ",");
You can also add your column names and values to an array and implode(",", $array) so you don't have to use rtrim
Instead of using
$array .= array(':$columnname' => $_POST[$columnname],);
and applying rtrim on results, I'd suggest the easier and failsafe method:
$array[':$columnname'] = $_POST[$columnname];

remove entry from array with value = NULL [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
remove element from array based on its value?
I have this array
$arr = array(
'key1'=>'value1',
'key2'=>NULL,
'key3'=>'value2'
);
if I do implode(',',$arr); I get: value1,,value2 (notice the empty space)
Is there a way to skip that NULL values? To get something like this:
value1,value2
I could traverse all the array and unset manually the key where the value is NULL, but it's a bit an overkill doens't it?
Edit:
To save time Maybe I could do just one loop to iterate over the array, and in the same loop I check for null values and if isn't null I append it the ','
like this:
foreach($arr as $k=>$v) {
if ($v !== NULL) {
echo $v.',';
}
}
The problem here is that I have a final ',' at the end.
Edit
As gordon asked, it ran this test (1000000 iterations)
First using array_filter:
$pairsCache = array('key1'=>'value1','key2'=>NULL,'key3'=>'value3',
'key4'=>'value4','key5'=>'value5');
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
$pairs = array_filter($pairsCache,function($v){return $v !== NULL;});
$keys = array_keys($pairs);
//> keys
$query .= implode(',',$keys ) . ") VALUES ( '";
//> values
$query .= implode("','",$pairs) . "')";
}
Time: 7.5949399471283
Query: "INSERT INTO tbl (key1,key3,key4,key5) VALUES ( 'value1','value3','value4','value5')"
Second using only one loop:
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
foreach($pairsCache as $k=>$v) {
if ($v!==NULL) {
$keys .= $k.',';
$values .= "'{$v}',";
}
}
$keys=rtrim($keys,',');
$values=rtrim($values,',');
$query = $query . $keys . ') VALUES ( ' . $values . ')';
}
Time: 4.1640941333771
Query: INSERT INTO tbl (key1,key3,key4,key5,) VALUES ( 'value1','value3','value4','value5')
$arr = array_filter($arr);
array_filter() removes every value, that evaluates to false from $arr.
If you need finer control, you can pass a callback as second argument
arr = array_filter($arr, function ($item) { return !is_null($item);});
At last of course you can iterate over the array yourself
foreach (array_keys($arr) $key) {
if (is_null($arr[$key])) unset($arr[$key]);
}
Note, that there is no downside, if you filter and output in two separate steps
You can use array_filter():
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
implode(',', array_filter($arr));
There is no possibility to do this using only implode().
You can traverse all the array (as you said) maybe in a wrapper my_implode() function, or you can use something less elegant such as:
trim(preg_replace('/[,]+/', ',', implode(',', $arr)), ',');
You can simply use bellow code.
Edited.
function nullFilter($val)
{
return $val !== NULL;
}
$arr = array( 'key1'=>'value1', 'key2'=>NULL, 'key3'=>'value2' );
$filteredArray = array_filter($arr,"nullFilter");
echo implode(',', $filteredArray);
Cheers!
Prasad.

Categories