[php] Fatal error: Call to a member function bind_param() on boolean

I'm busy on a function that gets settings from a DB, and suddenly, I ran into this error:

Fatal error: Call to a member function bind_param() on boolean in C:\xampp2\htdocs\application\classes\class.functions.php on line 16

Normally, this would mean that I'm selecting stuff from unexisting tables and stuff. But in this case, I 'm not...

Here's the getSetting function:

public function getSetting($setting)
{
    $query = $this->db->conn->prepare('SELECT value, param FROM ws_settings WHERE name = ?');
    $query->bind_param('s', $setting);
    $query->execute();
    $query->bind_result($value, $param);
    $query->store_result();
    if ($query->num_rows() > 0)
    {
        while ($query->fetch()) 
        {
            return $value;
            if ($param === '1')
            {
                $this->tpl->createParameter($setting, $value);
            }
        }
    }
    else
    {
        __('invalid.setting.request', $setting);
    }
}

The $this->db variable is passed through a constructor. In case of need, here is it:

public function __construct($db, $data, $tpl)
{
    $this->db = $db;
    $this->tpl = $tpl;
    $this->data = $data;
    $this->data->setData('global', 'theme', $this->getSetting('theme'));
}

Also, since I'm making use of a database, my database connection:

class Database
{
    private $data;

    public function __construct($data)
    {
    $this->data = $data;
    $this->conn = new MySQLi(
      $this->data->getData('database', 'hostname'), 
      $this->data->getData('database', 'username'), 
      $this->data->getData('database', 'password'), 
      $this->data->getData('database', 'database')
    );
    if ($this->conn->errno)
    {
        __('failed.db.connection', $this->conn->errno);
    }
    date_default_timezone_set('Europe/Amsterdam');
}

I've already tested the connection, 100% positive that it works as intended. I'm setting the DB connection things in a configuration file:

'database' => array(
    'hostname' => '127.0.0.1',
    'username' => 'root',
    'password' => ******,
    'database' => 'wscript'
)

Now the weird thing is; the table exists, the requested setting exists, the DB exists, but still, that error won't leave. Here's some proof that the DB is correct:

IMG

This question is related to php mysql mysqli

The answer is


Even when the query syntax is correct, prepare could return false, if there was a previous statement and it wasn't closed. Always close your previous statement with

$statement->close();

If the syntax is correct, the following query will run well too.


Following two are the most probable cause of this issue:

  1. Spelling mistake either in column names or table name
  2. Previously established statement is not closed. Just close it before making the prepared statement.

$stmt->close(); // <<<-----This fixed the issue for me

$stmt = $conn->prepare("Insert statement");

prepare return a boolean only when it fails therefore FALSE, to avoid the error you need to check if it is True first before executing:

$sql = 'SELECT value, param FROM ws_settings WHERE name = ?';
if($query = $this->db->conn->prepare($sql)){
    $query->bind_param('s', $setting);
    $query->execute();
    //rest of code here
}else{
   //error !! don't go further
   var_dump($this->db->error);
}

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.


Sometimes explicitly stating your table column names (especially in an insert query) may help. For example, the query:

INSERT INTO tableName(param1, param2, param3) VALUES(?, ?, ?)

may work better as opposed to:

INSERT INTO tableName VALUES(?, ?, ?)

Sometimes, it is also because of a wrong table name or column name in the prepare statement.

See this.


Any time you get the...

"Fatal error: Call to a member function bind_param() on boolean"

...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!

First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.

Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();

The error is generic and not very helpful to you in solving what is going on.

With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
    $query->bind_param('s', $definition);
    $query->execute();
    // any additional code you need would go here.
} else {
    $error = $mysqli->errno . ' ' . $mysqli->error;
    echo $error; // 1054 Unknown column 'foo' in 'field list'
}

If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.

If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.


Another situation that can cause this problem is incorrect casting in your queries.

I know it may sound obvious, but I have run into this by using tablename instead of Tablename. Check your queries, and make sure that you're using the same case as the actual names of the columns in your table.


I noticed that the error was caused by me passing table field names as variables i.e. I sent:

$stmt = $this->con->prepare("INSERT INTO tester ($test1, $test2) VALUES (?, ?)");

instead of:

$stmt = $this->con->prepare("INSERT INTO tester (test1, test2) VALUES (?, ?)");

Please note the table field names contained $ before field names. They should not be there such that $field1 should be field1.


This particular error has very little to do with the actual error. Here is my similar experience and the solution...

I had a table that I use in my statement with |database-name|.login composite name. I thought this wouldn't be a problem. It was the problem indeed. Enclosing it inside square brackets solved my problem ([|database-name|].[login]). So, the problem is MySQL preserved words (other way around)... make sure your columns too are not failing to this type of error scenario...


In my experience the bind_param was fine but I had mistaken the database name so, I changed only the database name in the connection parameter and it worked perfectly.

I had defined root path to indicate the root folder, include path to include folder and base url for the home url of website. This will be used for calling them anywhere they are required.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to mysqli

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO) mysqli_real_connect(): (HY000/2002): No such file or directory mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it Call to a member function fetch_assoc() on boolean in <path> How can I enable the MySQLi extension in PHP 7? Fatal error: Call to a member function bind_param() on boolean Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\ How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL) Object of class mysqli_result could not be converted to string in mysqli::query(): Couldn't fetch mysqli