Search code examples
phpmysqlibindparam

bind_param Error 500


I have the following script called via javascript POST

$target = $_POST['id'];
$sid = $_POST['sid'];

$sql = 'DELETE FROM `subusers` WHERE `subusers.uid`=?';
$stmt = $conn->prepare($sql);
if($stmt === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error, E_USER_ERROR);
}
echo $target;
$stmt->bind_param('i', $target);
$stmt->execute();

Whenever executed, for some reason it crashes with POST http://xx.php 500 (Internal Server Error). When bind_param is deleted, it works fine. The PHP also communicates with the script that called it, I tried sending the value of $target back to the script and alerting it and it shows a good value. I also tried $target=1 just for the sake of declaring it as an integer but it changed nothing. The whole mess in the query is just me trying to fix it in case there was a keyword somewhere.

Error code:

PHP Warning: mysqli::prepare(): Couldn't fetch mysqli in /var/www/html/delpar.php on line 12, referer:

PHP Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/delpar.php on line 17, referer:


Solution

  • There are are few issues here causing your prepare()/bind_param()/execute() to fail. The first thing spotted visually is incorrect quoting on the table.column included in your DELETE statement's WHERE clause. MySQL's identifier quoting requires that if quoted, each segment of the identifier be wrapped in its own pair of backticks.

    // Correct quoting
    $sql = 'DELETE FROM `subusers` WHERE `subusers`.`uid`=?';
    //-----------------------------------^^^^^^^^^^^^^^^^^
    

    Always when developing and testing code, it helps to enable PHP's display_errors ini directive, which would print errors and warnings to the screen rather than requiring you to dig into error logs (also recommended error_reporting = E_ALL). But in any case, most default setups log PHP errors to the web server's error log, such as /var/log/apache2/error.log or /var/log/httpd/error_log.

    Based on the first error message:

    PHP Warning: mysqli::prepare(): Couldn't fetch mysqli in /var/www/html/delpar.php on line 12

    It is apparent that your MySQLi connection object in $conn was either closed or never correctly connected to begin with. Look to earlier code to verify that $conn->close() has not already been called.