Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli bind_param does not set $stmt->error or $stmt->errno

Tags:

php

mysqli

According to the php manual you can retrieve errors in any prepared statement method by interrogating $stmt->error and $stmt->errno however the bind_param method never seems to set these on an error, can anyone else confirm this? or tell me what I am missing please?

For example:

echo "Start\n";
$db = new mysqli('localhost','test','xxxxxx','test');

$val = 1;

$st = $db->prepare('insert into tblTest set field1=?');
if($st == false)
{
    printf("prepare: %s %d\n",$db->error,$st->errno);
}

$rs = $st->bind_param('is', $val);
if($rs == false)
{
    printf("bind_param: %s %d\n",$st->error,$st->errno);
}

$rs = $st->execute();
if($rs == false)
{
    printf("execute: %s %d\n",$st->error,$st->errno);
}

$rs = $st->close();
if($rs == false)
{
    printf("close: %s %d\n",$st->error,$st->errno);
}
echo "Finish\n";

Running the above from the command line displays:

Start
PHP Warning:  mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in test.php on line 14
bind_param: 0
execute: No data supplied for parameters in prepared statement 2031
Finish

So php is seeing this as a Warning, bind_param is returning false, but error & errno are not set. execute is also failing and has correctly set error & errno

Is this a bug?

like image 423
Chris Avatar asked Jan 16 '23 04:01

Chris


1 Answers

MySQLi::error and MySQLi::errno are containers for error codes and messages returned by the RDBMS to PHP, not for errors encountered in the PHP code when setting up the statement. An incorrect call to bind_param() (with insufficient parameters) does apparently not communicate with the RDBMS, and thus won't receive its error from the RDBMS.

According to the docs, bind_param() returns a boolean FALSE on failure. So you will need to verify that it was called successfully.

$rs = $st->bind_param('is', $val);
if ($rs) {
  $st->execute();
}
like image 200
Michael Berkowski Avatar answered Jan 19 '23 00:01

Michael Berkowski