19

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Run
  • 54,938
  • 169
  • 450
  • 748

8 Answers8

24

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>';
}
rray
  • 2,518
  • 1
  • 28
  • 38
  • Probably not a good idea to make a custom function name identical to a native function name. I don't know if it is wise to set default parameter values that will break your function. – mickmackusa Nov 16 '22 at 21:10
13

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!

Run
  • 54,938
  • 169
  • 450
  • 748
  • 1
    Null values in your params array will break your dynamic binding call FYI – Gabriel Alack Dec 16 '14 at 21:02
  • 4
    The variable `$bind_name` is acually unused and `$$bind_name` makes the code confusing, while `$$` does _not_ have any special meaning in PHP. The same goes for `$var` and `$$var`. – Minding Nov 06 '18 at 16:02
  • NOTE: From the PHP manual: "Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values." Source: https://www.php.net/manual/en/mysqli-stmt.bind-param.php – I try so hard but I cry harder May 29 '20 at 16:06
  • https://www.php.net/manual/en/language.variables.variable.php `$$bind_name` actually means _variable variables_, which creates a variable named after the content of the `$bind_name`-variable assigning the value to it via `$$bind_name = "value";` and getting collected by the `$bind_names` array, for it to contain **references as needed**. So there are varables created named `$bind0,$bind1,...` and those are prefilled with the values. Works fine for me from 5.6..8.2. But as of 8.1 I would rather give that new $stmt->execute($data) a try: https://stackoverflow.com/a/74515082/2054633 – Juergen Jul 04 '23 at 14:37
9

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));
Matt Raines
  • 4,149
  • 8
  • 31
  • 34
6

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
  • The problem is that PDO is **much** slower than mysqli. And even slower than the older mysql. – Julian F. Weinert Apr 02 '13 at 11:23
  • 3
    @Julian: To say `PDO` is _much_ slower [is a bit much](http://jnrbsn.com/2010/06/mysqli-vs-pdo-benchmarks). The difference in performance is too small to be likely to be the main bottleneck (if noticeable at all) – Elias Van Ootegem Sep 11 '13 at 10:01
  • 1
    Thanks for correcting. I read a benchmark where the difference was more significant. And my own tests had more remarkable results. – Julian F. Weinert Sep 12 '13 at 09:50
  • @Julian it's been slow as flippin christmas everytime i used it. mysqli is so much faster i can't justify the convenience. but i'm leaning towards it. – r3wt Nov 10 '14 at 13:16
3

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): mysqli_result|array
    {
        $stmt = $this->mysqli->prepare($sql);
        $stmt->execute($data);
        return $stmt->get_result() ?: []; // if get_result() returns false, return an empty array so that the foreach doesn't choke
    }
}

$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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

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);
Sal Celli
  • 1,391
  • 1
  • 8
  • 5
-2

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.

Jeff Solomon
  • 459
  • 6
  • 21
  • 2
    this approach has been relevant ten years ago. You may want to notice the existing answer that takes ten times less code and requires no additional functions at all. It's generally quite a good idea to learn from the answers that already exist. – Your Common Sense Mar 14 '21 at 07:29
  • Awesome, thanks for that; so friendly of you. I'm just a beginner, give me a break. – Jeff Solomon Mar 14 '21 at 07:33
  • Sorry for bothering you again, but I just noticed a problem in your code. binding a single parameter for the IN operator won't give you any good results, effectively using only the first value from the comma-separated string. In your case, `WHERE status IN ("1,2,3,4")` is actually `WHERE status = 1`. You need to split that string and use separate values, generating the equal number of placeholders dynamically, as shown [here](https://phpdelusions.net/mysqli_examples/prepared_statement_with_in_clause) – Your Common Sense Mar 14 '21 at 07:58
  • @YourCommonSense ok, now that was very helpful, thank you. I just noticed that the query wasn't returning the desired results and wasn't sure why. I guess I spend some time trying some of the other mentioned solutions, although I couldn't fully make sense of them as they aren't fully articulated. Will take me some hacking through it to figure out. But thanks, I appreciate you actually reading through my work. – Jeff Solomon Mar 14 '21 at 19:03
  • [Here is your function rewritten](https://phpize.online/?phpses=408dcc13ef3466957932d672c6ccc28f) doing the correct binding for the array. It is using a [simple helper function to run mysqli queries](https://phpdelusions.net/mysqli/simple) I wrote – Your Common Sense Mar 14 '21 at 19:18
  • Oh man, that's a lot cleaner. Thanks for helping me out; I'm sure you have better things to do so I really appreciate it. – Jeff Solomon Mar 14 '21 at 19:33
-2

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.

Storm
  • 1
  • 2
  • fixed, missed that typo – Storm Nov 21 '22 at 00:41
  • Added comment showing what my fix adds, this isn't the best solution but it's just a minor improvement to an already accepted answer. – Storm Nov 21 '22 at 14:44
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33200854) – IRTFM Nov 21 '22 at 23:21
  • goodluck finding the answer to the question – Storm Nov 22 '22 at 03:45