mysqli : bind param where search parameters are conditional - php

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;
}

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.

Mysql search function

I am trying to setup a search function where i can either type in what i want or i can select it from a drop down menu, however when the fields are blank i want it to show everything.
Right now when i search for something it will work however when the fields are blank it does not show anything at all. I am using prepare and bind_params to setup the mysql query which is why it is making it difficult to setup because if the variable is empty im not sure how to easily remove that section of the query and also change the amount of variables that are being binded to the query. Here is the query
$stmt = $conn->prepare("SELECT * FROM re_tblcombinationlist WHERE active != ? AND ModifierKey = ? AND (LootItem1Key = ? OR LootItem2Key = ? ) ORDER BY ReportedOn DESC LIMIT ? , ?");
$stmt->bind_param("isssii", $i = 0, $modifier, $lootsearch, $lootsearch, $limits, $max);
$recent1 = infoo($stmt);
I tried to solve it by adding this if then statement but it didnt change anything
if(!isset($_POST["modifier"])){
$modifier = '';
}else{
$modifier = clean($_POST["modifier"]);
}
if(!isset($_POST["lootsearch"])){
$lootsearch = '';
}else{
$lootsearch = clean($_POST["lootsearch"]);
}
Basically if modifier or lootsearch are empty i dont want that section to be in the mysql query, which is easy to do however it then makes it very difficult to deal with the amount of variables to bind so i was trying to find a way to make it search everything if the variable is empty.
Thanks
I think that i found a solution to your problem based on this: http://php.net/manual/en/mysqli-stmt.bind-param.php#109256
First create this class:
class BindParam {
private $values = array();
private $types = '';
public function add( $type, $value ){
$this->values[] = $value;
$this->types .= $type;
}
public function get() {
return array_merge(array($this->types), $this->values);
}
}
After this, make sure you import that class in your code and then use insert the following lines in your search file:
//User inputs, just for testing
$active = 0;
$modifier = 5;
$lootsearch = 'item';
$limits = 3;
$max = 5;
//Conditional binding
$bindParam = new BindParam();
$binds = array();
$binds[] = 'active = ?';
$bindParam->add('i', $active);
$query = "SELECT * FROM re_tblcombinationlist WHERE ";
if (!empty($modifier)) {
$binds[] = 'ModifierKey = ?';
$bindParam->add('s', $modifier);
}
if (!empty($lootsearch)) {
$binds[] = ' (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ';
$bindParam->add('s', $lootsearch);
$bindParam->add('s', $lootsearch);
}
$query .= implode(" AND ", $binds);
$query .= " ORDER BY ReportedOn DESC LIMIT ? , ?";
$bindParam->add('i', $limits);
$bindParam->add('i', $max);
//Uncomment this for debugging
//echo $query . '<br/>';
//Using the above user inputs query should be:
//SELECT * FROM re_tblcombinationlist WHERE active = ? AND ModifierKey = ? AND (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ORDER BY ReportedOn DESC LIMIT ? , ?
//var_dump($bindParam->get());
//Maybe you have to experiment a bit with those lines
$stmt = $conn->prepare($query);
$stmt->bind_param($bindParam->get());
$recent1 = infoo($stmt);
The final solution that i chose to go with on this was a combination of my last post and Kostas post.
First we add the class:
class BindParam {
private $values = array();
private $types = '';
public function add( $type, &$value ){
$this->values[] = &$value;
$this->types .= $type;
}
public function get() {
$array = array_merge(array($this->types), $this->values);
foreach($array as $key => $value)
$refs[$key] = &$array[$key];
return $refs;
}
}
Then we add this code where ever we want to use the query dynamically:
//User inputs, just for testing
$active = 0;
$modifier = 5;
$lootsearch = 'item';
$limits = 3;
$max = 5;
//Conditional binding
$bindParam = new BindParam();
$binds = array();
$binds[] = 'active = ?';
$bindParam->add('i', $active);
$query = "SELECT * FROM re_tblcombinationlist WHERE ";
if (!empty($modifier)) {
$binds[] = ' AND ModifierKey = ?';
$bindParam->add('s', $modifier);
}
if (!empty($lootsearch)) {
$binds[] = ' AND (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ';
$bindParam->add('s', $lootsearch);
$bindParam->add('s', $lootsearch);
}
$query .= implode(" ", $binds);//removed the AND to allow for AND and OR
$query .= " ORDER BY ReportedOn DESC LIMIT ? , ?";
$bindParam->add('i', $limits);
$bindParam->add('i', $max);
//Uncomment this for debugging
//echo $query . '<br/>';
//Using the above user inputs query should be:
//SELECT * FROM re_tblcombinationlist WHERE active = ? AND ModifierKey = ? AND (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ORDER BY ReportedOn DESC LIMIT ? , ?
//var_dump($bindParam->get());
//Maybe you have to experiment a bit with those lines
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $bindParam->get());//Required in order to use the array given by bindParam->get()
$recent1 = infoo($stmt);
Alright I figured out how to get this to work. First off, most of what Kostas had stated is the solution and I'm not trying to take credit for his work however it needed to be changed slightly to work properly.
First i added a function
function reference($arr){
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
and then i changed this(from Kostas' code)
$stmt->bind_param($bindParam->get());
to
call_user_func_array(array($stmt, 'bind_param'), reference($bindParam->get()));

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.

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