How to 'really' detect integers from DB?
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.
精彩评论