LunaD03 LunaD03 - 2 years ago 66
PHP Question

bind_param() Fatal Error in PHP MySQLi

So I know this error/question has been posted/asked a lot on SO, but none of the answers helped me and I kept getting this error:

Fatal error: Call to a member function bind_param() on a non-object


Here is the relevant code:


$connect = new mysqli(connection info);

$search = $_POST["search"];

$sql = $connect->prepare("SELECT name, seller FROM products
WHERE name LIKE '%' + ? + '%';");
$sql->bind_param("s", $search);


?>


I believe it has something to do with the like clause, but I am not sure. I am a inexperienced SQL and PHP coder.

Help is greatly appreciated!

Answer Source

You have two options: add the wildcard inside the variable, or inside the query.

Inside the query, you use the CONCAT function

$sql = $connect->prepare("SELECT name, seller FROM products
                          WHERE name LIKE CONCAT('%', ? , '%')");
$sql->bind_param("s", $search);

Outside of the query, you can pass it in with the bind_param, which is good if you decide you want to do an exact search instead of a wildcard search

$sql = $connect->prepare("SELECT name, seller FROM products
                          WHERE name LIKE ?");
$sql->bind_param("s", '%'.$search.'%');

If the bind_param does not work, you can add the wildcards before the statement:

$search = '%'.$search.'%';
$sql->bind_param("s", $search);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download