[HELP] PHP - Array to Bind Param (MySQLi)

Discussion in 'PHP' started by RastaLulz, Mar 12, 2011.

  1. #1
    Hello,

    I'm in a bit of a pickle trying to create a function for MySQL that will allow me to put all of my values in an array, and then execute them in bind_param (MySQLi function).

    Example:
    
    <?php
    function execute($query, $values) {
      global $mysqli;
      
      $run = $mysqli->prepare($query);
      
      /* I need help getting PHP to omit the line below and execute it. */
      $run->bind_param($values[0], $values[1], $values[2], $values[3]); /* I want it to look like this. */
      /* I need help getting PHP to omit the line above and execute it. */
    
      $run->execute();
    }
    
    execute('UPDATE users SET name = ?, email = ? WHERE id = ?;',
            Array('ssi', $_POST['name'], $_POST['email'], $_SESSION['id'])
            );
    
    PHP:
    The solution maybe simple or not, but I can't seem to think of a solution for some reason. :?:



    EDIT
    I've almost got it, but am having one last issue.

    This doesn't work:
    
    $mysqli = new mysqli($_CONFIG['mysql']['host'], $_CONFIG['mysql']['user'], $_CONFIG['mysql']['pass'], $_CONFIG['mysql']['db']);
    
    function execute($query, $params) {
      global $mysqli;
      $run = $mysqli->prepare($query);
      call_user_func_array(array($run, 'bind_param'), $params);
      $run->execute();
      $run->store_result();
      return $run->num_rows;
    }
    echo execute('SELECT username FROM users WHERE username = ?;', Array('s', 'RastaLulz'));
    
    PHP:
    Returns the following error:
    
    Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in C:\xampp\htdocs\ProCMS\DevBestCMS\test.php on line 12
    
    Code (markup):
    This does:
    
    $mysqli = new mysqli($_CONFIG['mysql']['host'], $_CONFIG['mysql']['user'], $_CONFIG['mysql']['pass'], $_CONFIG['mysql']['db']);
    
    function execute($query, $params) {
      global $mysqli;
      $run = $mysqli->prepare($query);
      call_user_func_array(array($run, 'bind_param'), Array('s', 'RastaLulz'));
      $run->execute();
      $run->store_result();
      return $run->num_rows;
    }
    echo execute('SELECT username FROM users WHERE username = ?;', Array('s', 'RastaLulz'));
    
    PHP:
    How would I get the first one to work? I don't understand what's the difference between the array being directly defined inside of it, and a variable that contains the array.

    EDIT:
    Apparently the issue above was a bug in PHP 5.3.1.

    I corrected the issue by running the following code:
    
    $tmp = array();
    foreach($params as $key => $value) $tmp[$key] = &$params[$key];
    
    PHP:
    A bit silly that I have to do this, but it works.
     
    Last edited: Mar 12, 2011
    RastaLulz, Mar 12, 2011 IP