0

I can seem to get this code to work, I receive the error "Commands out of sync; you can't run this command now" when it gets to " $stmt->execute(); "

I'm using eclipse to debug it but I'm more familiar with procedural code, it appears to be running ok upto the stmt->execute part.

the code is below

function execSQL($sql, $params, $close){
$mysqli = new mysqli("localhost", "web_user", "jaitec", "ebay");

$stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");

call_user_func_array(array($stmt, 'bind_param'), refValues($params));

$stmt->execute();

if($close){
    $result = $mysqli->affected_rows;
} else {
    $result = $mysqli->affected_rows;
    $meta = $stmt->result_metadata();

    while ( $field = $meta->fetch_field() ) {
        $parameters[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), refValues($parameters));

    while ( $stmt->fetch() ) {
        $x = array();
        foreach( $row as $key => $val ) {
            $x[$key] = $val;
        }
        $results[] = $x;
    }

    $result = $results;
}

$stmt->close();
$mysqli->close();

return  $result;
}


function refValues(&$arr) // Changed $arr to reference for PHP v7.1.7
{
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;
}

$_REQUEST['term']   = "m8 knob";
$part_1     =   "knob";
$part_2 =   "m8";
execSQL("SELECT * FROM web_search WHERE part_no LIKE ? AND part_no LIKE ?", array('ss', $part_1, $part_2), false);
jai
  • 1
  • Writing a wrapper around the database driver is usually pushing you one step closer to writing your own ORM, a problem that's been solved many times over. Are you sure this is worth doing instead of using an existing solution? – tadman Aug 07 '18 at 22:31
  • I'm trying to find a simple solution where I can build the sql statement with a variable number of "ANDs" and try to stop injection type problems... I'm not that advanced enough to know what a ORM is. – jai Aug 08 '18 at 00:51
  • I have looked at other Qs & As but as far as I can see I'm only trying to run one query and not two at once.. – jai Aug 08 '18 at 00:57
  • That's the paradox: You often end up writing an ORM before you know what one is, or how it's supposed to work, meaning your solution is often considerably different from anything other programmers are familiar with. Have a look at existing examples like [Idorm](https://github.com/j4mie/idiorm), [Doctrine](http://www.doctrine-project.org/), [Propel](http://propelorm.org/), [RedBeanPHP](https://redbeanphp.com/), or [Eloquent](https://laravel.com/docs/master/eloquent) before embarking on what's going to be a huge project. – tadman Aug 09 '18 at 15:37

0 Answers0