I'm experimenting with joining databases in php using prepared statements. I got this error:
Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? OR users.class LIKE ? OR users.email LIKE ?' at line 3 in C:\xampp\htdocs\Burza\includes\functions.inc.php:335 Stack trace: #0 #0 C:\xampp\htdocs\Burza\includes\functions.inc.php(335): mysqli_query(Object(mysqli), 'SELECT * FROM p...') #1 C:\xampp\htdocs\Burza\buy.php(20): getProductsBySearch(Object(mysqli), '%summer%') #2 {main} thrown in C:\xampp\htdocs\Burza\includes\functions.inc.php
I think it's because of the LIKE keyword, but I don't know what to do about it. All of the names of the tables and rows are correct
My code looks like this:
function getProductsBySearch($conn, $search){
$sql = "SELECT * FROM products
JOIN users ON products.userid = users.id
WHERE users.name LIKE ? OR users.surname LIKE ? OR users.class LIKE ? OR users.email LIKE ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("location: ../index.php?error=stmtfailed");
exit();
}
$search = "%".$search."%";
mysqli_stmt_bind_param($stmt, "ssss", $search, $search, $search, $search);// s = string
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_query($conn, $sql);
$products = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_stmt_close($stmt);
return $products;
}
Can somebody explain to me why it's happening and how to fix it?
I tried changing the * symbol to more specific part in my database - products.id and it didn't help. And I tried using '%".?."%' and it didn't work as well.