I'm trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I've found this post here on Stack Overflow where Amber posted an answer with the following code:
Original post:
How to make a proper mysqli extension class with prepared statements?
"Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:"
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
function stmt_bind_params($stmt, $fields, $data) {
// Dynamically build up the arguments for bind_param
$paramstr = '';
$params = array();
foreach($fields as $key)
{
if(is_float($data[$key]))
$paramstr .= 'd';
elseif(is_int($data[$key]))
$paramstr .= 'i';
else
$paramstr .= 's';
$params[] = $data[$key];
}
array_unshift($params, $stmt, $paramstr);
// and then call bind_param with the proper arguments
call_user_func_array('mysqli_stmt_bind_param', $params);
}
I tried studying the code to understand what it does and I've made the second function work properly but I don't know what I should do to be able to utilize the first function. How do I use it to retrieve an array similar to mysqli_result:: fetch_assoc()?
I want to be able to utilize the result in such a way like you used to do with:
while ($row = mysql_fetch_array($result)){
echo $row['foo']." ".$row['bar'];
}
Okay, here is a way to do it:
Edited, to fix bug when fetching multiple rows
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
/*
In my real app the below code is wrapped up in a class
But this is just for example's sake.
You could easily throw it in a function or class
*/
// This will loop through params, and generate types. e.g. 'ss'
$types = '';
foreach($params as $param) {
if(is_int($param)) {
$types .= 'i'; //integer
} elseif (is_float($param)) {
$types .= 'd'; //double
} elseif (is_string($param)) {
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
// Start stmt
$query = $this->connection->stmt_init(); // $this->connection is the mysqli connection instance
if($query->prepare($sql)) {
// Bind Params
call_user_func_array(array($query,'bind_param'),$params);
$query->execute();
// Get metadata for field names
$meta = $query->result_metadata();
// initialise some empty arrays
$fields = $results = array();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
$fieldCount = count($fieldNames);
// Bind Results
call_user_func_array(array($query,'bind_result'),$fields);
$i=0;
while ($query->fetch()){
for($l=0;$l<$fieldCount;$l++) $results[$i][$fieldNames[$l]] = $fields[$fieldNames[$l]];
$i++;
}
$query->close();
// And now we have a beautiful
// array of results, just like
//fetch_assoc
echo "<pre>";
print_r($results);
echo "</pre>";
}
The Answer from Emmanuel works fine, if only one row is selected! If the query select multiple rows, the $results-Array holds for every row a result, but the result is always filled with the last entry. With a little change in the fetch()-while it work well.
$sqlStmt is an string, filled with the mysql-query
$params is an array, filled with the variables that should passed
$results is an empty array, that holds the result
if (!is_string($sqlStmt) || empty($sqlStmt)) {
return false;
}
// initialise some empty arrays
$fields = array();
$results = array();
if ($stmt = $this->prepare($sqlStmt)) {
// bind params if they are set
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
}
}
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
// execute query
$stmt->execute();
// Get metadata for field names
$meta = $stmt->result_metadata();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
}
Just to compare excellent answers from #Emmanuel and #matzino with the code you can get if choose PDO over mysqli:
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
$stm = $query->prepare($sql);
$stm->execute($params);
$results = $stm->fetchAll(); // or fetch() or fetchColumn() depends on expected type
whoops, that's all?
After using the answer above I have figured out that there was some cleanup needed for myself, particularly the 'fieldNames[]' portion. The code below is in procedural style. I hope it will come of use to someone.
I cut the code from a class I made that can dynamically query data. There are a few things I removed to make it easier to read. In the class I have I allow the user to define definitions tables and foreign keys so that data entry on the front-end is restricted as well as filter and sort options for said related data. These are all parameters I removed as well as the automated query builder.
$query = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
////////////// GENERATE PARAMETER TYPES IF ANY //////////////
// This will loop through parameters, and generate types. ex: 'ss'
$types = '';
$params_size = sizeof($params);
if($params_size > 0)
{
foreach($params as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}else if(is_float($param))
{
$types .= 'd'; //double
}else if(is_string($param))
{
$types .= 's'; //string
}else
{
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
}
////////////////////////////////////////////////////////////
// This is the tricky part to dynamically create an array of
// variables to use to bind the results
//below from http://php.net/manual/en/mysqli-result.fetch-field.php
/*
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def Reserved for default value, currently always ""
db Database (since PHP 5.3.6)
catalog The catalog name, always "def" (since PHP 5.3.6)
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
*/
/// FIELD TYPE REFERENCE ///
/*
numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246
dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13
strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
*/
if($stmt = mysqli_prepare($db_link, $query))
{
// BIND PARAMETERS IF ANY //
if($params_size > 0)
{
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($params));
}
mysqli_stmt_execute($stmt);
$meta = mysqli_stmt_result_metadata($stmt);
$field_names = array();
$field_length = array();
$field_type = array();
$output_data = array();
/// THIS GET THE NAMES OF THE FIELDS AND ASSIGNS NEW VARIABLES USING THE FIELD NAME. THESE VARIABLES ARE THEN SET TO NULL ///
$count = 0;
while($field = mysqli_fetch_field($meta))
{
$field_names[$count] = $field->name;// field names
$var = $field->name;
$$var = null;
$field_names_variables[$var] = &$$var;// fields variables using the field name
$field_length[$var] = $field->length;// field length as defined in table
$field_type[$var] = $field->type;// field data type as defined in table (numeric return)
$count++;
}
setFieldLengthInfo($field_length);
setFieldTypesInfo($field_type);
$field_names_variables_size = sizeof($field_names_variables);
call_user_func_array(array($stmt, 'bind_result'), $field_names_variables);
$count = 0;
while(mysqli_stmt_fetch($stmt))
{
for($l = 0; $l < $field_names_variables_size; $l++)
{
$output_data[$count][$field_names[$l]] = $field_names_variables[$field_names[$l]];/// THIS SETS ALL OF THE FINAL DATA USING THE DYNAMICALLY CREATED VARIABLES ABOVE
}
$count++;
}
mysqli_stmt_close($stmt);
echo "<pre>";
print_r($output_data);
echo "</pre>";
}
function makeValuesReferenced($arr)
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
Related
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.
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.
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.
I would need a good structure for building queries where search parameters are conditional using mysqli prepared statement. $query -> bind_param('sss',$date,$time,$place);
I dont know how to apply 'sss' and '$date,$time,$place' parameters in order later. Can you pass them as variable?
Old MySQL way:
<?php
// date is obligatory
$date = mysql_real_escape_string($_GET["date"]);
$query="SELECT * FROM dbase WHERE date='$date'";
// time field is custom
if(!empty($_GET["time"])) {
$time= mysql_real_escape_string($_GET["time"]);
$buildQuery[] = "time='$time'";
}
// place field is also custom
if(!empty($_GET["place"])) {
$place= mysql_real_escape_string($_GET["place"]);
$buildQuery[] = "place='$place'";
}
// building query
if(!empty($build)) {
$query .= ' AND '.implode(' AND ',$build).' ORDER BY date';
}
?>
This is a good case where PDO is far easier than MySQLi:
$query="SELECT * FROM dbase";
$terms = array("date" => $date);
$params = array();
// time field is custom
if(isset($_GET["time"])) {
$terms["sType"] = $time;
}
// place field is also custom
if(isset($_GET["place"])) {
$terms["place"] = $place;
}
// building query
if(!empty($terms)) {
$query .= "WHERE " . implode(" AND ",
array_map(function($term) { return "$term = ?"; }, array_keys($terms));
$params = array_values($terms);
}
$query .= "ORDER BY date";
$stmt = $pdo->pepare($query);
$stmt->execute($params);
PS: I have to question whether you meant to have your sType column contain both time and place. Seems like you're breaking relational database best practices. Unless it's just a typo.
untested, but you should be able to do something like this
$types = array();
$vals = array();
if(isset($_GET["time"])) {
$types[] = 's';
$vals[] = $_GET["time"];
$buildQuery[] = "sType = ?";
}
//...etc...
$args = array_merge(array(join($types)), $vals);
$callable = array($mysqli, 'bind_param');
call_user_func_array($callable, $args));
http://php.net/manual/en/language.types.callable.php
but, there's another approach. Just use logic in the sql:
select *
from tbl
where (date = ? or ? = '')
and (time = ? or ? = '')
and (place = ? or ? = '')
The above assumes you'll bind each arg twice, and bind them as strings, but binding an empty string if the query string param wasnt set... You could bind them as null if needed too via something like (date = ? or ? is null).
$mysqli->bind_param('ssssss', $date,$date, $time,$time, $place,$place);
ps, the mysql optimizer will make short work of that simple logic.
Based on goat's reply, here's a full and tested answer with an UPDATE statement where the fields to be updated are conditional. I have used a very simple table structure with 3 fields: ID (auto increment), Varchar1 (varchar255) and Varchar2 (varchar255). In this script, I want to update the two varchar fields for the first three records. Based on this script, it's very easy to conditionally add or remove fields to be updated.
$mysqli = new mysqli(...);
$types = array();
$vals = array();
$query = array();
// varchar1
$types[] = 's';
$vals[] = 'foo1';
$query[] = "varchar1=?";
// varchar2
$types[] = 's';
$vals[] = 'foo2';
$query[] = "varchar2=?";
$sql = "UPDATE test SET ".implode(",", $query)." WHERE id IN (1,2,3)";
$stmt = $mysqli->prepare($sql);
$args = array_merge(array(implode($types)), $vals);
$callable = array($stmt, 'bind_param');
call_user_func_array($callable, refValues($args));
$stmt->execute();
function refValues($arr) {
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
I'm trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I've found this post here on Stack Overflow where Amber posted an answer with the following code:
Original post:
How to make a proper mysqli extension class with prepared statements?
"Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:"
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
function stmt_bind_params($stmt, $fields, $data) {
// Dynamically build up the arguments for bind_param
$paramstr = '';
$params = array();
foreach($fields as $key)
{
if(is_float($data[$key]))
$paramstr .= 'd';
elseif(is_int($data[$key]))
$paramstr .= 'i';
else
$paramstr .= 's';
$params[] = $data[$key];
}
array_unshift($params, $stmt, $paramstr);
// and then call bind_param with the proper arguments
call_user_func_array('mysqli_stmt_bind_param', $params);
}
I tried studying the code to understand what it does and I've made the second function work properly but I don't know what I should do to be able to utilize the first function. How do I use it to retrieve an array similar to mysqli_result:: fetch_assoc()?
I want to be able to utilize the result in such a way like you used to do with:
while ($row = mysql_fetch_array($result)){
echo $row['foo']." ".$row['bar'];
}
Okay, here is a way to do it:
Edited, to fix bug when fetching multiple rows
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
/*
In my real app the below code is wrapped up in a class
But this is just for example's sake.
You could easily throw it in a function or class
*/
// This will loop through params, and generate types. e.g. 'ss'
$types = '';
foreach($params as $param) {
if(is_int($param)) {
$types .= 'i'; //integer
} elseif (is_float($param)) {
$types .= 'd'; //double
} elseif (is_string($param)) {
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
// Start stmt
$query = $this->connection->stmt_init(); // $this->connection is the mysqli connection instance
if($query->prepare($sql)) {
// Bind Params
call_user_func_array(array($query,'bind_param'),$params);
$query->execute();
// Get metadata for field names
$meta = $query->result_metadata();
// initialise some empty arrays
$fields = $results = array();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
$fieldCount = count($fieldNames);
// Bind Results
call_user_func_array(array($query,'bind_result'),$fields);
$i=0;
while ($query->fetch()){
for($l=0;$l<$fieldCount;$l++) $results[$i][$fieldNames[$l]] = $fields[$fieldNames[$l]];
$i++;
}
$query->close();
// And now we have a beautiful
// array of results, just like
//fetch_assoc
echo "<pre>";
print_r($results);
echo "</pre>";
}
The Answer from Emmanuel works fine, if only one row is selected! If the query select multiple rows, the $results-Array holds for every row a result, but the result is always filled with the last entry. With a little change in the fetch()-while it work well.
$sqlStmt is an string, filled with the mysql-query
$params is an array, filled with the variables that should passed
$results is an empty array, that holds the result
if (!is_string($sqlStmt) || empty($sqlStmt)) {
return false;
}
// initialise some empty arrays
$fields = array();
$results = array();
if ($stmt = $this->prepare($sqlStmt)) {
// bind params if they are set
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
}
}
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
// execute query
$stmt->execute();
// Get metadata for field names
$meta = $stmt->result_metadata();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
}
Just to compare excellent answers from #Emmanuel and #matzino with the code you can get if choose PDO over mysqli:
$sql = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
$stm = $query->prepare($sql);
$stm->execute($params);
$results = $stm->fetchAll(); // or fetch() or fetchColumn() depends on expected type
whoops, that's all?
After using the answer above I have figured out that there was some cleanup needed for myself, particularly the 'fieldNames[]' portion. The code below is in procedural style. I hope it will come of use to someone.
I cut the code from a class I made that can dynamically query data. There are a few things I removed to make it easier to read. In the class I have I allow the user to define definitions tables and foreign keys so that data entry on the front-end is restricted as well as filter and sort options for said related data. These are all parameters I removed as well as the automated query builder.
$query = "SELECT `first_name`,`last_name` FROM `users` WHERE `country` =? AND `state`=?";
$params = array('Australia','Victoria');
////////////// GENERATE PARAMETER TYPES IF ANY //////////////
// This will loop through parameters, and generate types. ex: 'ss'
$types = '';
$params_size = sizeof($params);
if($params_size > 0)
{
foreach($params as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}else if(is_float($param))
{
$types .= 'd'; //double
}else if(is_string($param))
{
$types .= 's'; //string
}else
{
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
}
////////////////////////////////////////////////////////////
// This is the tricky part to dynamically create an array of
// variables to use to bind the results
//below from http://php.net/manual/en/mysqli-result.fetch-field.php
/*
name The name of the column
orgname Original column name if an alias was specified
table The name of the table this field belongs to (if not calculated)
orgtable Original table name if an alias was specified
def Reserved for default value, currently always ""
db Database (since PHP 5.3.6)
catalog The catalog name, always "def" (since PHP 5.3.6)
max_length The maximum width of the field for the result set.
length The width of the field, as specified in the table definition.
charsetnr The character set number for the field.
flags An integer representing the bit-flags for the field.
type The data type used for this field
decimals The number of decimals used (for integer fields)
*/
/// FIELD TYPE REFERENCE ///
/*
numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246
dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13
strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
*/
if($stmt = mysqli_prepare($db_link, $query))
{
// BIND PARAMETERS IF ANY //
if($params_size > 0)
{
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($params));
}
mysqli_stmt_execute($stmt);
$meta = mysqli_stmt_result_metadata($stmt);
$field_names = array();
$field_length = array();
$field_type = array();
$output_data = array();
/// THIS GET THE NAMES OF THE FIELDS AND ASSIGNS NEW VARIABLES USING THE FIELD NAME. THESE VARIABLES ARE THEN SET TO NULL ///
$count = 0;
while($field = mysqli_fetch_field($meta))
{
$field_names[$count] = $field->name;// field names
$var = $field->name;
$$var = null;
$field_names_variables[$var] = &$$var;// fields variables using the field name
$field_length[$var] = $field->length;// field length as defined in table
$field_type[$var] = $field->type;// field data type as defined in table (numeric return)
$count++;
}
setFieldLengthInfo($field_length);
setFieldTypesInfo($field_type);
$field_names_variables_size = sizeof($field_names_variables);
call_user_func_array(array($stmt, 'bind_result'), $field_names_variables);
$count = 0;
while(mysqli_stmt_fetch($stmt))
{
for($l = 0; $l < $field_names_variables_size; $l++)
{
$output_data[$count][$field_names[$l]] = $field_names_variables[$field_names[$l]];/// THIS SETS ALL OF THE FINAL DATA USING THE DYNAMICALLY CREATED VARIABLES ABOVE
}
$count++;
}
mysqli_stmt_close($stmt);
echo "<pre>";
print_r($output_data);
echo "</pre>";
}
function makeValuesReferenced($arr)
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}