PHP - How to substitute array as host parameter in prepared statement - php

I am able to bind values of type int, str, bool and null but I am unable to bind array type.
I have tried both functions, i.e. bindValue and bindParam but neither of them worked.
How can I accomplish this ?
// a helper function to map Sqlite data type
function getArgType($arg) {
switch (gettype($arg)) {
case 'double': return SQLITE3_FLOAT;
case 'integer': return SQLITE3_INTEGER;
case 'boolean': return SQLITE3_INTEGER;
case 'NULL': return SQLITE3_NULL;
case 'string': return SQLITE3_TEXT;
default:
throw new \InvalidArgumentException('Argument is of invalid type '.gettype($arg));
}
}
$sql = "SELECT * FROM table_name WHERE id IN (?)";
$params = [[10, 9, 6]]; // array of array
$dbpath = '/path/to/sqlite.sqlite';
$db = new SQLite3($dbPath, SQLITE3_OPEN_READONLY);
$stmt = $db->prepare($sql);
try {
foreach ($params as $index => $val) {
if (is_array($val)) {
/************* I am stuck here *************/
$ok = $stmt->bindParam($index + 1, $val);
// Using bindValue also didn't worked!
} else {
$ok = $stmt->bindValue($index + 1, $val, getArgType($val));
}
if (!$ok) {
throw new Exception("Unable to bind param: $val");
}
}
} catch (Exception $ex) {
// NO exception is thrown from bindValue() or bindParam()
$reason = "Error in binding statement. " . $ex->getMessage();
die($reason);
}
$result = $stmt->execute();
$data = [];
while ($row = $result->fetchArray($mode)) {
$data[] = $row;
}
var_dump($data);
Edit: I already tried replacing single ? with required number of question marks in param array, but then it is working only if my array has less than 1000 values! I think it's a limitation of how statements are prepared in SQLite3 in PHP.

Unfortunately this is not possible! You cannot bind an array.
The easiest solution for you problem would be the following:
Create the SQL-Query with one placeholder (?) per value in the array
Bind each value by iterating over the array.
But there are also another options (e.g. a sub-SELECT)
More information here (even if it's a Java question, it is nearly the same topic/problem because the database type doesn't matter in this case)
EDIT: Normally, the SQL Limit for bound parameters is set so 999, but you can change it if you need to.

You cannot bind arrays as a list for an IN (?) clause. Each value in the IN list must get its distinct place holder.
To make this dynamic, first determine the array of values and then dynamically build the SQL.
This would be your code:
$arrayParam = [10, 9, 6];
$placeHolders = implode(',', array_fill(0, count($arrayParam), '?'));
$sql = "SELECT * FROM table_name WHERE id IN ($placeHolders) AND name = ?";
// Merge the "array" parameter values with any other parameter values
// into one non-nested array:
$params = array_merge($arrayParam, ['myname']);
// ...
foreach ($params as $index => $val) {
// No sub arrays allowed:
$ok = $stmt->bindValue($index + 1, $val, getArgType($val));
// ... etc

I would propose a work-around in what you try to do. Pass the query result to a temporary table.
// a helper function to map Sqlite data type
function getArgType($arg) {
switch (gettype($arg)) {
case 'double': return SQLITE3_FLOAT;
case 'integer': return SQLITE3_INTEGER;
case 'boolean': return SQLITE3_INTEGER;
case 'NULL': return SQLITE3_NULL;
case 'string': return SQLITE3_TEXT;
default:
throw new \InvalidArgumentException('Argument is of invalid type '.gettype($arg));
}
}
function getTempValues() {
$sql = "SELECT * FROM `myTemp`";
$params = [$in]; // array of array
$dbpath = '/path/to/sqlite.sqlite';
$db = new SQLite3($dbPath, SQLITE3_OPEN_READONLY);
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$data = [];
while ($row = $result->fetchArray($mode)) {
$data[] = $row;
}
return $data;
}
function addToTemp($in) {
$sql = "SELECT * INTO `myTemp` FROM `table_name` WHERE `id` = ?";
$params = [$in]; // array of array
$dbpath = '/path/to/sqlite.sqlite';
$db = new SQLite3($dbPath, SQLITE3_OPEN_READONLY);
$stmt = $db->prepare($sql);
if(is_array($in)) {
foreach($in as $newValue) {
addToTemp($newValue);
}
} else {
try {
foreach ($params as $index => $val) {
$ok = $stmt->bindValue($index + 1, $val, getArgType($val));
if (!$ok) {
throw new Exception("Unable to bind param: $val");
}
}
} catch (Exception $ex) {
// NO exception is thrown from bindValue() or bindParam()
$reason = "Error in binding statement. " . $ex->getMessage();
die($reason);
}
$stmt->execute();
}
return getTempValues();
}
print_r(addToTemp([10,9,6]));

(Caveat: This answer was written before the 'mysql' tag has been removed; I don't know if it addslashes works for sqlite3.)
In PHP, given $list as an array of values destined for an IN list:
$list = array(1, 2, 'abcd', 'double quote: "', "apostrophe: don't");
$ins = implode(', ', array_map(
function($a) {
return "'" . addslashes($a) . "'";
}, $list));
echo $sql = "... IN ($ins) ...";;
yields
... IN ('1', '2', 'abcd', 'double quote: \"', 'apostrophe: don\'t') ...
(Yes, this could be done with a normal for loop, without using array_map and an "anonymous function".)
Don't worry; quotes around numbers ('123') is OK for numeric columns.

You can add ? placeholder as many as number of items in your array
Select * from table_a where field in (?,?,?,?,?,?,?,.....)
If they are bigger than 1000 then split them into two or more queries.

Related

PHP mysqli bind_param array as parameter [duplicate]

I have been learning to use prepared and bound statements for my sql queries, and I have come out with this so far, it works okay but it is not dynamic at all when comes to multiple parameters or when there no parameter needed,
public function get_result($sql,$parameter)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
$stmt->bind_param("s", $parameter);
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# close statement
$stmt->close();
}
This is how I call the object classes,
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
Sometimes I don't need to pass in any parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
";
print_r($output->get_result($sql));
Sometimes I need only one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1'));
Sometimes I need only more than one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1','Tk'));
So, I believe that this line is not dynamic enough for the dynamic tasks above,
$stmt->bind_param("s", $parameter);
To build a bind_param dynamically, I have found this on other posts online.
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
And I tried to modify some code from php.net but I am getting nowhere,
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$array_of_param[$key] = &$arr[$key];
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
}
Why? Any ideas how I can make it work?
Or maybe there are better solutions?
Using PHP 5.6 you can do this easy with help of unpacking operator(...$var) and use get_result() insted of bind_result()
public function get_custom_result($sql,$types = null,$params = null) {
$stmt = $this->mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
if(!$stmt->execute()) return false;
return $stmt->get_result();
}
Example:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "SELECT * FROM root_contacts_cfm WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC";
$res = $output->get_custom_result($sql, 'ss',array('1','Tk'));
while($row = res->fetch_assoc()){
echo $row['fieldName'] .'<br>';
}
found the answer for mysqli:
public function get_result($sql,$types = null,$params = null)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
//$stmt->bind_param("s", $parameter);
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# the commented lines below will return values but not arrays
# bind result variables
//$stmt->bind_result($id);
# fetch value
//$stmt->fetch();
# return the value
//return $id;
# close statement
$stmt->close();
}
then:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "
SELECT *
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'s',array('1')));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql, 'ss',array('1','Tk')));
mysqli is so lame when comes to this. I think I should be migrating to PDO!
With PHP 5.6 or higher:
$stmt->bind_param(str_repeat("s", count($data)), ...$data);
With PHP 5.5 or lower you might (and I did) expect the following to work:
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $data));
...but mysqli_stmt::bind_param expects its parameters to be references whereas this passes a list of values.
You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.
$references_to_data = array();
foreach ($data as &$reference) { $references_to_data[] = &$reference; }
unset($reference);
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $references_to_data));
Or maybe there are better solutions??
This answer doesn't really help you much, but you should seriously consider switching to PDO from mysqli.
The main reason for this is because PDO does what you're trying to do in mysqli with built-in functions. In addition to having manual param binding, the execute method can take an array of arguments instead.
PDO is easy to extend, and adding convenience methods to fetch-everything-and-return instead of doing the prepare-execute dance is very easy.
Since PHP8.1 gave a facelift to MySQLi's execute() method, life got much easier for this type of task.
Now you no longer need to fuss and fumble with manually binding values to placeholders. Just pass in an indexed array of values and feed that data directly into execute().
Code: (PHPize.online Demo)
class Example
{
private $mysqli;
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
public function get(string $sql, array $data): object
{
$stmt = $this->mysqli->prepare($sql);
$stmt->execute($data);
return $stmt->get_result();
}
}
$example = new Example($mysqli);
foreach ($example->get('SELECT * FROM example', []) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ?', ['Ned']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ? OR flag = ?', ['Bill', 'foo']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
We have #Dharman to thank for this feature.
I solved it by applying a system similar to that of the PDO. The SQL placeholders are strings that start with the double-point character. Ex .:
:id, :name, or :last_name
Then you can specify the data type directly inside the placeholder string by adding the specification letters immediately after the double-point and appending an underline character before the mnemonic variable. Ex .:
:i_id (i=integer), :s_name or :s_last_name (s=string)
If no type character is added, then the function will determine the type of the data by analyzing the php variable holding the data. Ex .:
$id = 1 // interpreted as an integer
$name = "John" // interpreted as a string
The function returns an array of types and an array of values with which you can execute the php function mysqli_stmt_bind_param() in a loop.
$sql = 'SELECT * FROM table WHERE code = :code AND (type = :i_type OR color = ":s_color")';
$data = array(':code' => 1, ':i_type' => 12, ':s_color' => 'blue');
$pattern = '|(:[a-zA-Z0-9_\-]+)|';
if (preg_match_all($pattern, $sql, $matches)) {
$arr = $matches[1];
foreach ($arr as $word) {
if (strlen($word) > 2 && $word[2] == '_') {
$bindType[] = $word[1];
} else {
switch (gettype($data[$word])) {
case 'NULL':
case 'string':
$bindType[] = 's';
break;
case 'boolean':
case 'integer':
$bindType[] = 'i';
break;
case 'double':
$bindType[] = 'd';
break;
case 'blob':
$bindType[] = 'b';
break;
default:
$bindType[] = 's';
break;
}
}
$bindValue[] = $data[$word];
}
$sql = preg_replace($pattern, '?', $sql);
}
echo $sql.'<br>';
print_r($bindType);
echo '<br>';
print_r($bindValue);
I generally use the mysqli prepared statements method and frequently have this issue when I'm dynamically building the query based on the arguments included in a function (just as you described). Here is my approach:
function get_records($status = "1,2,3,4", $user_id = false) {
global $database;
// FIRST I CREATE EMPTY ARRAYS TO STORE THE BIND PARAM TYPES AND VALUES AS I BUILD MY QUERY
$type_arr = array();
$value_arr = array();
// THEN I START BUILDING THE QUERY
$query = "SELECT id, user_id, url, dr FROM sources";
// THE FIRST PART IS STATIC (IT'S ALWAYS IN THE QUERY)
$query .= " WHERE status IN (?)";
// SO I ADD THE BIND TYPE "s" (string) AND ADD TO THE TYPE ARRAY
$type_arr[] = "s";
// AND I ADD THE BIND VALUE $status AND ADD TO THE VALUE ARRAY
$value_arr[] = $status;
// THE NEXT PART OF THE QUERY IS DYNAMIC IF THE USER IS SENT IN OR NOT
if ($user_id) {
$query .= " AND user_id = ?";
// AGAIN I ADD THE BIND TYPE AND VALUE TO THE CORRESPONDING ARRAYS
$type_arr[] = "i";
$value_arr[] = $user_id;
}
// THEN I PREPARE THE STATEMENT
$stmt = mysqli_prepare($database, $query);
// THEN I USE A SEPARATE FUNCTION TO BUILD THE BIND PARAMS (SEE BELOW)
$params = build_bind_params($type_arr, $value_arr);
// PROPERLY SETUP THE PARAMS FOR BINDING WITH CALL_USER_FUNC_ARRAY
$tmp = array();
foreach ($params as $key => $value) $tmp[$key] = &$params[$key];
// PROPERLY BIND ARRAY TO THE STATEMENT
call_user_func_array(array($stmt , 'bind_param') , $tmp);
// FINALLY EXECUTE THE STATEMENT
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
return $result;
}
And here is the build_bind_params function:
// I PASS IN THE TYPES AND VALUES ARRAY FROM THE QUERY ABOVE
function build_bind_params($types, $values) {
// THEN I CREATE AN EMPTY ARRAY TO STORE THE FINAL OUTPUT
$bind_array = array();
// THEN I CREATE A TEMPORARY EMPTY ARRAY TO GROUP THE TYPES; THIS IS NECESSARY BECAUSE THE FINAL ARRAY ALL THE TYPES MUST BE A STRING WITH NO SPACES IN THE FIRST KEY OF THE ARRAY
$i = array();
foreach ($types as $type) {
$i[] = $type;
}
// SO I IMPLODE THE TYPES ARRAY TO REMOVE COMMAS AND ADD IT AS KEY[0] IN THE BIND ARRAY
$bind_array[] = implode('', $i);
// FINALLY I LOOP THROUGH THE VALUES AND ADD THOSE AS SUBSEQUENT KEYS IN THE BIND ARRAY
foreach($values as $value) {
$bind_array[] = $value;
}
return $bind_array;
}
The output of this build_bind_params function looks like this:
Array ( [0] => isiisi [1] => 1 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 )
You can see the [0] key is all the bind types with no spaces and no commas. and the rest of the keys represent the corresponding values. Note that the above output is an example of what the output would look like if I had 6 bind values all with different bind types.
Not sure if this is a smart way to do it or not, but it works and no performance issues in my use cases.
An improvement to answer by #rray
function query($sql, $types = null, $params = null)
{
$this->stmt = $this->conn->prepare($sql);
if ($types && $params) {
$this->stmt->bind_param($types, ...$params);
}
if (!$this->stmt->execute())
return false;
return $this->stmt->get_result();
}
This improvement only calls the bind function if the parameter and values for binding are set, on php the previous version by rray which gave an error incase you called the function with only an sql statement which is not ideal.

Is there any way to create a prepared statement based on user selection? [duplicate]

I have been learning to use prepared and bound statements for my sql queries, and I have come out with this so far, it works okay but it is not dynamic at all when comes to multiple parameters or when there no parameter needed,
public function get_result($sql,$parameter)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
$stmt->bind_param("s", $parameter);
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# close statement
$stmt->close();
}
This is how I call the object classes,
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
Sometimes I don't need to pass in any parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
";
print_r($output->get_result($sql));
Sometimes I need only one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1'));
Sometimes I need only more than one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1','Tk'));
So, I believe that this line is not dynamic enough for the dynamic tasks above,
$stmt->bind_param("s", $parameter);
To build a bind_param dynamically, I have found this on other posts online.
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
And I tried to modify some code from php.net but I am getting nowhere,
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$array_of_param[$key] = &$arr[$key];
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
}
Why? Any ideas how I can make it work?
Or maybe there are better solutions?
Using PHP 5.6 you can do this easy with help of unpacking operator(...$var) and use get_result() insted of bind_result()
public function get_custom_result($sql,$types = null,$params = null) {
$stmt = $this->mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
if(!$stmt->execute()) return false;
return $stmt->get_result();
}
Example:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "SELECT * FROM root_contacts_cfm WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC";
$res = $output->get_custom_result($sql, 'ss',array('1','Tk'));
while($row = res->fetch_assoc()){
echo $row['fieldName'] .'<br>';
}
found the answer for mysqli:
public function get_result($sql,$types = null,$params = null)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
//$stmt->bind_param("s", $parameter);
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# the commented lines below will return values but not arrays
# bind result variables
//$stmt->bind_result($id);
# fetch value
//$stmt->fetch();
# return the value
//return $id;
# close statement
$stmt->close();
}
then:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "
SELECT *
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'s',array('1')));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql, 'ss',array('1','Tk')));
mysqli is so lame when comes to this. I think I should be migrating to PDO!
With PHP 5.6 or higher:
$stmt->bind_param(str_repeat("s", count($data)), ...$data);
With PHP 5.5 or lower you might (and I did) expect the following to work:
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $data));
...but mysqli_stmt::bind_param expects its parameters to be references whereas this passes a list of values.
You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.
$references_to_data = array();
foreach ($data as &$reference) { $references_to_data[] = &$reference; }
unset($reference);
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $references_to_data));
Or maybe there are better solutions??
This answer doesn't really help you much, but you should seriously consider switching to PDO from mysqli.
The main reason for this is because PDO does what you're trying to do in mysqli with built-in functions. In addition to having manual param binding, the execute method can take an array of arguments instead.
PDO is easy to extend, and adding convenience methods to fetch-everything-and-return instead of doing the prepare-execute dance is very easy.
Since PHP8.1 gave a facelift to MySQLi's execute() method, life got much easier for this type of task.
Now you no longer need to fuss and fumble with manually binding values to placeholders. Just pass in an indexed array of values and feed that data directly into execute().
Code: (PHPize.online Demo)
class Example
{
private $mysqli;
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
public function get(string $sql, array $data): object
{
$stmt = $this->mysqli->prepare($sql);
$stmt->execute($data);
return $stmt->get_result();
}
}
$example = new Example($mysqli);
foreach ($example->get('SELECT * FROM example', []) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ?', ['Ned']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ? OR flag = ?', ['Bill', 'foo']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
We have #Dharman to thank for this feature.
I solved it by applying a system similar to that of the PDO. The SQL placeholders are strings that start with the double-point character. Ex .:
:id, :name, or :last_name
Then you can specify the data type directly inside the placeholder string by adding the specification letters immediately after the double-point and appending an underline character before the mnemonic variable. Ex .:
:i_id (i=integer), :s_name or :s_last_name (s=string)
If no type character is added, then the function will determine the type of the data by analyzing the php variable holding the data. Ex .:
$id = 1 // interpreted as an integer
$name = "John" // interpreted as a string
The function returns an array of types and an array of values with which you can execute the php function mysqli_stmt_bind_param() in a loop.
$sql = 'SELECT * FROM table WHERE code = :code AND (type = :i_type OR color = ":s_color")';
$data = array(':code' => 1, ':i_type' => 12, ':s_color' => 'blue');
$pattern = '|(:[a-zA-Z0-9_\-]+)|';
if (preg_match_all($pattern, $sql, $matches)) {
$arr = $matches[1];
foreach ($arr as $word) {
if (strlen($word) > 2 && $word[2] == '_') {
$bindType[] = $word[1];
} else {
switch (gettype($data[$word])) {
case 'NULL':
case 'string':
$bindType[] = 's';
break;
case 'boolean':
case 'integer':
$bindType[] = 'i';
break;
case 'double':
$bindType[] = 'd';
break;
case 'blob':
$bindType[] = 'b';
break;
default:
$bindType[] = 's';
break;
}
}
$bindValue[] = $data[$word];
}
$sql = preg_replace($pattern, '?', $sql);
}
echo $sql.'<br>';
print_r($bindType);
echo '<br>';
print_r($bindValue);
I generally use the mysqli prepared statements method and frequently have this issue when I'm dynamically building the query based on the arguments included in a function (just as you described). Here is my approach:
function get_records($status = "1,2,3,4", $user_id = false) {
global $database;
// FIRST I CREATE EMPTY ARRAYS TO STORE THE BIND PARAM TYPES AND VALUES AS I BUILD MY QUERY
$type_arr = array();
$value_arr = array();
// THEN I START BUILDING THE QUERY
$query = "SELECT id, user_id, url, dr FROM sources";
// THE FIRST PART IS STATIC (IT'S ALWAYS IN THE QUERY)
$query .= " WHERE status IN (?)";
// SO I ADD THE BIND TYPE "s" (string) AND ADD TO THE TYPE ARRAY
$type_arr[] = "s";
// AND I ADD THE BIND VALUE $status AND ADD TO THE VALUE ARRAY
$value_arr[] = $status;
// THE NEXT PART OF THE QUERY IS DYNAMIC IF THE USER IS SENT IN OR NOT
if ($user_id) {
$query .= " AND user_id = ?";
// AGAIN I ADD THE BIND TYPE AND VALUE TO THE CORRESPONDING ARRAYS
$type_arr[] = "i";
$value_arr[] = $user_id;
}
// THEN I PREPARE THE STATEMENT
$stmt = mysqli_prepare($database, $query);
// THEN I USE A SEPARATE FUNCTION TO BUILD THE BIND PARAMS (SEE BELOW)
$params = build_bind_params($type_arr, $value_arr);
// PROPERLY SETUP THE PARAMS FOR BINDING WITH CALL_USER_FUNC_ARRAY
$tmp = array();
foreach ($params as $key => $value) $tmp[$key] = &$params[$key];
// PROPERLY BIND ARRAY TO THE STATEMENT
call_user_func_array(array($stmt , 'bind_param') , $tmp);
// FINALLY EXECUTE THE STATEMENT
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
return $result;
}
And here is the build_bind_params function:
// I PASS IN THE TYPES AND VALUES ARRAY FROM THE QUERY ABOVE
function build_bind_params($types, $values) {
// THEN I CREATE AN EMPTY ARRAY TO STORE THE FINAL OUTPUT
$bind_array = array();
// THEN I CREATE A TEMPORARY EMPTY ARRAY TO GROUP THE TYPES; THIS IS NECESSARY BECAUSE THE FINAL ARRAY ALL THE TYPES MUST BE A STRING WITH NO SPACES IN THE FIRST KEY OF THE ARRAY
$i = array();
foreach ($types as $type) {
$i[] = $type;
}
// SO I IMPLODE THE TYPES ARRAY TO REMOVE COMMAS AND ADD IT AS KEY[0] IN THE BIND ARRAY
$bind_array[] = implode('', $i);
// FINALLY I LOOP THROUGH THE VALUES AND ADD THOSE AS SUBSEQUENT KEYS IN THE BIND ARRAY
foreach($values as $value) {
$bind_array[] = $value;
}
return $bind_array;
}
The output of this build_bind_params function looks like this:
Array ( [0] => isiisi [1] => 1 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 )
You can see the [0] key is all the bind types with no spaces and no commas. and the rest of the keys represent the corresponding values. Note that the above output is an example of what the output would look like if I had 6 bind values all with different bind types.
Not sure if this is a smart way to do it or not, but it works and no performance issues in my use cases.
An improvement to answer by #rray
function query($sql, $types = null, $params = null)
{
$this->stmt = $this->conn->prepare($sql);
if ($types && $params) {
$this->stmt->bind_param($types, ...$params);
}
if (!$this->stmt->execute())
return false;
return $this->stmt->get_result();
}
This improvement only calls the bind function if the parameter and values for binding are set, on php the previous version by rray which gave an error incase you called the function with only an sql statement which is not ideal.

Php mysqli bind_param with array [duplicate]

I have been learning to use prepared and bound statements for my sql queries, and I have come out with this so far, it works okay but it is not dynamic at all when comes to multiple parameters or when there no parameter needed,
public function get_result($sql,$parameter)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
$stmt->bind_param("s", $parameter);
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# close statement
$stmt->close();
}
This is how I call the object classes,
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
Sometimes I don't need to pass in any parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
";
print_r($output->get_result($sql));
Sometimes I need only one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1'));
Sometimes I need only more than one parameters,
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'1','Tk'));
So, I believe that this line is not dynamic enough for the dynamic tasks above,
$stmt->bind_param("s", $parameter);
To build a bind_param dynamically, I have found this on other posts online.
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
And I tried to modify some code from php.net but I am getting nowhere,
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$array_of_param[$key] = &$arr[$key];
call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params);
}
Why? Any ideas how I can make it work?
Or maybe there are better solutions?
Using PHP 5.6 you can do this easy with help of unpacking operator(...$var) and use get_result() insted of bind_result()
public function get_custom_result($sql,$types = null,$params = null) {
$stmt = $this->mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
if(!$stmt->execute()) return false;
return $stmt->get_result();
}
Example:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "SELECT * FROM root_contacts_cfm WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC";
$res = $output->get_custom_result($sql, 'ss',array('1','Tk'));
while($row = res->fetch_assoc()){
echo $row['fieldName'] .'<br>';
}
found the answer for mysqli:
public function get_result($sql,$types = null,$params = null)
{
# create a prepared statement
$stmt = $this->mysqli->prepare($sql);
# bind parameters for markers
# but this is not dynamic enough...
//$stmt->bind_param("s", $parameter);
if($types&&$params)
{
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
$return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
# execute query
$stmt->execute();
# these lines of code below return one dimentional array, similar to mysqli::fetch_assoc()
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$field->name] = &$$var;
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
return $parameters;
//print_r($parameters);
}
# the commented lines below will return values but not arrays
# bind result variables
//$stmt->bind_result($id);
# fetch value
//$stmt->fetch();
# return the value
//return $id;
# close statement
$stmt->close();
}
then:
$mysqli = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$output = new search($mysqli);
$sql = "
SELECT *
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql,'s',array('1')));
$sql = "
SELECT *
FROM root_contacts_cfm
WHERE root_contacts_cfm.cnt_id = ?
AND root_contacts_cfm.cnt_firstname = ?
ORDER BY cnt_id DESC
";
print_r($output->get_result($sql, 'ss',array('1','Tk')));
mysqli is so lame when comes to this. I think I should be migrating to PDO!
With PHP 5.6 or higher:
$stmt->bind_param(str_repeat("s", count($data)), ...$data);
With PHP 5.5 or lower you might (and I did) expect the following to work:
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $data));
...but mysqli_stmt::bind_param expects its parameters to be references whereas this passes a list of values.
You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.
$references_to_data = array();
foreach ($data as &$reference) { $references_to_data[] = &$reference; }
unset($reference);
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $references_to_data));
Or maybe there are better solutions??
This answer doesn't really help you much, but you should seriously consider switching to PDO from mysqli.
The main reason for this is because PDO does what you're trying to do in mysqli with built-in functions. In addition to having manual param binding, the execute method can take an array of arguments instead.
PDO is easy to extend, and adding convenience methods to fetch-everything-and-return instead of doing the prepare-execute dance is very easy.
Since PHP8.1 gave a facelift to MySQLi's execute() method, life got much easier for this type of task.
Now you no longer need to fuss and fumble with manually binding values to placeholders. Just pass in an indexed array of values and feed that data directly into execute().
Code: (PHPize.online Demo)
class Example
{
private $mysqli;
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
public function get(string $sql, array $data): object
{
$stmt = $this->mysqli->prepare($sql);
$stmt->execute($data);
return $stmt->get_result();
}
}
$example = new Example($mysqli);
foreach ($example->get('SELECT * FROM example', []) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ?', ['Ned']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
echo "\n---\n";
foreach ($example->get('SELECT * FROM example WHERE name = ? OR flag = ?', ['Bill', 'foo']) as $row) {
echo "<div>{$row['name']}</div>\n";
}
We have #Dharman to thank for this feature.
I solved it by applying a system similar to that of the PDO. The SQL placeholders are strings that start with the double-point character. Ex .:
:id, :name, or :last_name
Then you can specify the data type directly inside the placeholder string by adding the specification letters immediately after the double-point and appending an underline character before the mnemonic variable. Ex .:
:i_id (i=integer), :s_name or :s_last_name (s=string)
If no type character is added, then the function will determine the type of the data by analyzing the php variable holding the data. Ex .:
$id = 1 // interpreted as an integer
$name = "John" // interpreted as a string
The function returns an array of types and an array of values with which you can execute the php function mysqli_stmt_bind_param() in a loop.
$sql = 'SELECT * FROM table WHERE code = :code AND (type = :i_type OR color = ":s_color")';
$data = array(':code' => 1, ':i_type' => 12, ':s_color' => 'blue');
$pattern = '|(:[a-zA-Z0-9_\-]+)|';
if (preg_match_all($pattern, $sql, $matches)) {
$arr = $matches[1];
foreach ($arr as $word) {
if (strlen($word) > 2 && $word[2] == '_') {
$bindType[] = $word[1];
} else {
switch (gettype($data[$word])) {
case 'NULL':
case 'string':
$bindType[] = 's';
break;
case 'boolean':
case 'integer':
$bindType[] = 'i';
break;
case 'double':
$bindType[] = 'd';
break;
case 'blob':
$bindType[] = 'b';
break;
default:
$bindType[] = 's';
break;
}
}
$bindValue[] = $data[$word];
}
$sql = preg_replace($pattern, '?', $sql);
}
echo $sql.'<br>';
print_r($bindType);
echo '<br>';
print_r($bindValue);
I generally use the mysqli prepared statements method and frequently have this issue when I'm dynamically building the query based on the arguments included in a function (just as you described). Here is my approach:
function get_records($status = "1,2,3,4", $user_id = false) {
global $database;
// FIRST I CREATE EMPTY ARRAYS TO STORE THE BIND PARAM TYPES AND VALUES AS I BUILD MY QUERY
$type_arr = array();
$value_arr = array();
// THEN I START BUILDING THE QUERY
$query = "SELECT id, user_id, url, dr FROM sources";
// THE FIRST PART IS STATIC (IT'S ALWAYS IN THE QUERY)
$query .= " WHERE status IN (?)";
// SO I ADD THE BIND TYPE "s" (string) AND ADD TO THE TYPE ARRAY
$type_arr[] = "s";
// AND I ADD THE BIND VALUE $status AND ADD TO THE VALUE ARRAY
$value_arr[] = $status;
// THE NEXT PART OF THE QUERY IS DYNAMIC IF THE USER IS SENT IN OR NOT
if ($user_id) {
$query .= " AND user_id = ?";
// AGAIN I ADD THE BIND TYPE AND VALUE TO THE CORRESPONDING ARRAYS
$type_arr[] = "i";
$value_arr[] = $user_id;
}
// THEN I PREPARE THE STATEMENT
$stmt = mysqli_prepare($database, $query);
// THEN I USE A SEPARATE FUNCTION TO BUILD THE BIND PARAMS (SEE BELOW)
$params = build_bind_params($type_arr, $value_arr);
// PROPERLY SETUP THE PARAMS FOR BINDING WITH CALL_USER_FUNC_ARRAY
$tmp = array();
foreach ($params as $key => $value) $tmp[$key] = &$params[$key];
// PROPERLY BIND ARRAY TO THE STATEMENT
call_user_func_array(array($stmt , 'bind_param') , $tmp);
// FINALLY EXECUTE THE STATEMENT
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
return $result;
}
And here is the build_bind_params function:
// I PASS IN THE TYPES AND VALUES ARRAY FROM THE QUERY ABOVE
function build_bind_params($types, $values) {
// THEN I CREATE AN EMPTY ARRAY TO STORE THE FINAL OUTPUT
$bind_array = array();
// THEN I CREATE A TEMPORARY EMPTY ARRAY TO GROUP THE TYPES; THIS IS NECESSARY BECAUSE THE FINAL ARRAY ALL THE TYPES MUST BE A STRING WITH NO SPACES IN THE FIRST KEY OF THE ARRAY
$i = array();
foreach ($types as $type) {
$i[] = $type;
}
// SO I IMPLODE THE TYPES ARRAY TO REMOVE COMMAS AND ADD IT AS KEY[0] IN THE BIND ARRAY
$bind_array[] = implode('', $i);
// FINALLY I LOOP THROUGH THE VALUES AND ADD THOSE AS SUBSEQUENT KEYS IN THE BIND ARRAY
foreach($values as $value) {
$bind_array[] = $value;
}
return $bind_array;
}
The output of this build_bind_params function looks like this:
Array ( [0] => isiisi [1] => 1 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 )
You can see the [0] key is all the bind types with no spaces and no commas. and the rest of the keys represent the corresponding values. Note that the above output is an example of what the output would look like if I had 6 bind values all with different bind types.
Not sure if this is a smart way to do it or not, but it works and no performance issues in my use cases.
An improvement to answer by #rray
function query($sql, $types = null, $params = null)
{
$this->stmt = $this->conn->prepare($sql);
if ($types && $params) {
$this->stmt->bind_param($types, ...$params);
}
if (!$this->stmt->execute())
return false;
return $this->stmt->get_result();
}
This improvement only calls the bind function if the parameter and values for binding are set, on php the previous version by rray which gave an error incase you called the function with only an sql statement which is not ideal.

MySQL Insert failing dynamically but working directly

I've got a MySQL table with fields a1,a2,a3,b1,...,d1,d2, each field was declared as a BOOLEAN in the CREATE statement. (I also tried TINYINT(1) but had the same problem).
Then I have this PHP function which receives data from an HTML form:
public function add($a) {
$sql = "INSERT INTO property_classification
(a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
// creating the classification_id
// e.g. "a1a2a3" => ["a1","a2","a3"]
$classifications = str_split($a['classifications'], 2);
$data = array();
// compile $data array
foreach (self::$classification_fields as $classification) {
// if user array contained any classification, set to true
if (in_array($classification, $classifications)) {
$data[$classification] = "1"; // I tried `true` too
} else {
$data[$classification] = "0"; // I tried `false` here
}
}
// set type for binding PDO params
foreach ($data as $key=>$value) settype($data[$key], 'int'); // tried 'bool'
$this->db->query($sql, $data);
$a['classification_id'] = $this->db->lastInsertId();
$this->log($a['classification_id']); // Output: "0"
...
The output should be a valid ID from 1+, but the insert failed so the lastInsertId() returned 0.
I checked what $sql compiled to, it came to this:
INSERT INTO property_classification (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);
I also output $data with the code: implode(",",$data); and it gave me this output:
1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Which was perfect because the input was "a1a2".
The only problem now is I don't understand why the query is failing all the time, because I put the two bits together like so:
INSERT INTO property_classification (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) VALUES(1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
Then I executed that query in MySQL Query Browser and it worked.
So why is it failing through PDO?
DBO class
function query($sql, $data) {
try {
$this->query = $this->db->prepare($sql);
if (!is_null($data) && is_array($data))
$this->query->execute($data);
else
$this->query->execute();
} catch (PDOException $e) {
array_push($this->log, $e->getMessage());
}
}
Since you're actually passing an associative array to the PDO, you can bind to named parameters. The use of ? or positional placeholders require a standard indexed array. If you're against using named params, just replace $data[$classification] = with $data[] =
Try the below.
public function add($a) {
$sql = "INSERT INTO property_classification
(a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2)
VALUES(:a1,:a2,:a3,:b1,:b2,:b3,:b4,:b5,:b6,:b7,:b8,:c1,:c2,:c3,:d1,:d2);";
// creating the classification_id
// e.g. "a1a2a3" => ["a1","a2","a3"]
$classifications = str_split($a['classifications'], 2);
$data = array();
// compile $data array
foreach (self::$classification_fields as $classification)
$data[$classification] = in_array($classification, $classifications) ? 1 : 0;
$this->db->query($sql, $data);
$a['classification_id'] = $this->db->lastInsertId();
$this->log($a['classification_id']); // Output: "0"

Use one bind_param() with variable number of input vars

I try to use variable binding like this:
$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);
but some of the $_POST['...'] might be empty so I don't want to update them in the DB.
It's not practical to take into account all the different combination of empty $_POST['...'] and although I can build the string " UPDATE mytable SET..." to my needs, bind_param() is a different beast.
I could try building its call as a string and use eval() on it but it doesn't feel right :(
You could use the call_user_func_array function to call the bind_param method with a variable number or arguments:
$paramNames = array('myvar1', 'myvar2', /* ... */);
$params = array();
foreach ($paramNames as $name) {
if (isset($_POST[$name]) && $_POST[$name] != '') {
$params[$name] = $_POST[$name];
}
}
if (count($params)) {
$query = 'UPDATE mytable SET ';
foreach ($params as $name => $val) {
$query .= $name.'=?,';
}
$query = substr($query, 0, -1);
$query .= 'WHERE id = ?';
$stmt = $mysqli->prepare($query);
$params = array_merge(array(str_repeat('s', count($params))), array_values($params));
call_user_func_array(array(&$stmt, 'bind_param'), $params);
}
This is what I use to do mysqli prepared statements with a variable amount of params. It's part of a class I wrote. It propably is overkill for what you need but it should show you the right direction.
public function __construct($con, $query){
$this->con = $con;
$this->query = $query;
parent::__construct($con, $query);
//We check for errors:
if($this->con->error) throw new Exception($this->con->error);
}
protected static $allowed = array('d', 'i', 's', 'b'); //allowed types
protected static function mysqliContentType($value) {
if(is_string($value)) $type = 's';
elseif(is_float($value)) $type = 'd';
elseif(is_int($value)) $type = 'i';
else throw new Exception("type of '$value' is not string, int or float");
return $type;
}
//This function checks if a given string is an allowed mysqli content type for prepared statement (s, d, b, or i)
protected static function mysqliAllowedContentType($s){
return in_array($s, self::$allowed);
}
public function feed($params){
//These should all be empty in case this gets used multiple times
$this->paramArgs = array();
$this->typestring = '';
$this->params = $params;
$this->paramArgs[0] = '';
$i = 0;
foreach($this->params as $value){
//We check the type:
if(is_array($value)){
$temp = array_keys($value);
$type = $temp[0];
$this->params[$i] = $value[$type];
if(!self::mysqliAllowedContentType($type)){
$type = self::mysqliContentType($value[$type]);
}
}
else{
$type = self::mysqliContentType($value);
}
$this->typestring .= $type;
//We build the array of values we pass to the bind_params function
//We add a refrence to the value of the array to the array we will pass to the call_user_func_array function. Thus say we have the following
//$this->params array:
//$this->params[0] = 'foo';
//$this->params[1] = 4;
//$this->paramArgs will become:
//$this->paramArgs[0] = 'si'; //Typestring
//$this->paramArgs[1] = &$this->params[0];
//$this->paramArgs[2] = &$this->params[1].
//Thus using call_user_func_array will call $this->bind_param() (which is inherented from the mysqli_stmt class) like this:
//$this->bind_param( 'si', &$this->params[0], &$this->params[1] );
$this->paramArgs[] = &$this->params[$i];
$i++;
}
unset($i);
$this->paramArgs[0] = $this->typestring;
return call_user_func_array(array(&$this, 'bind_param'), $this->paramArgs);
}
You use it like this:
$prep = new theClassAboveHere( $mysqli, $query );
$prep->feed( array('string', 1, array('b', 'BLOB DATA') );
The class should extend the mysqli_stmt class.
I hope this helps you in the right direction.
If you wan't I could also post the whole class, it includes variable results binding.
It is marginally more clear to build your statement using an array:
$params = array();
$fragments = array();
foreach($_POST as $col => $val)
{
$fragments[] = "{$col} = ?";
$params[] = $val;
}
$sql = sprintf("UPDATE sometable SET %s", implode(", ", $fragments));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($params);
array_insert does not exist, i'm guessing he refers to some home made function, but i'm not sure exactly what it does ... inserts the parameter types onto the array somewhere in the beginning i would guess since the value 0 is passed but hey it could be in the end too ;)
Build it as a string, but put your values into an array and pass that to bindd_param. (and substitute ?'s for values in your SQL string.
$stmt = $mysqli->prepare("UPDATE mytable SET myvar1=?, myvar2=... WHERE id = ?")) {
$stmt->bind_param("ss...", $_POST['myvar1'], $_POST['myvar2']...);
For example:
$args = array();
$sql = "UPDATE sometable SET ";
$sep = "";
$paramtypes = "";
foreach($_POST as $key => $val) {
$sql .= $sep.$key." = '?'";
$paramtypes .= "s"; // you'll need to map these based on name
array_push($args, $val);
$sep = ",";
}
$sql .= " WHERE id = ?";
array_push($args, $id);
array_insert($args, $paramtypes, 0);
$stmt = $mysqli->prepare($sql);
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
$stmt->bind_param($args);

Categories