0

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!

LunaD03
  • 13
  • 4

4 Answers4

1

Not exactly sure what you're trying to do with the +, but if you want '%$search%' then:

$search = '%'.$_POST["search"].'%';

$sql = $connect->prepare("SELECT name, seller FROM products
                          WHERE name LIKE ?");
$sql->bind_param("s", $search);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

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);
aynber
  • 22,380
  • 8
  • 50
  • 63
0

you put the wildcards into the bind itself like this and use the PHP concatenation operator .

$sql = $connect->prepare("SELECT name, seller FROM products
                          WHERE name LIKE ?");
$sql->bind_param("s", '%' . $search . '%');
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

The other answers already show how to fix it, but just to explicitly state it in case you want to know, the reason you got the error

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

is that your call to prepare failed because of a syntax error in your SQL statement.

While you can use + as a string concatenation operator in some other databases, in MySQL it's strictly a math operator, as far as I know.

If you follow these instructions to configure your connection such that MySQL errors will raise PHP exceptions, you'll be able to see the specific error that MySQL returns instead of just getting a seemingly-unrelated PHP error when you try to use the unsuccessfully prepared statement.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80