mariadb PHP程序:使用LIKE关键字时语法错误[duplicate]

xxb16uws  于 2023-02-08  发布在  PHP
关注(0)|答案(1)|浏览(135)
    • 此问题在此处已有答案**:

You have an error in your SQL syntax error?(2个答案)
5小时前关门了。
我在php中尝试使用预准备语句连接数据库,遇到了以下错误:
未捕获的mysqli_sql_异常:SQL语法中有错误;查看与您的MariaDB服务器版本对应的手册,以了解在C:\xampp\htdocs\Burza\includes\functions. inc. php:335中第3行"?OR users.class LIKE?OR www.example.com LIKE?"附近使用的正确语法:users.emailmysqli_query(对象(mysqli),'选择 * 从页面...')#1 C:\xampp\htdocs\Burza\buy.php(20):按搜索获取产品(对象(mysqli),' % summer %')#2 {main}抛出于C:\xampp\htdocs\Burza\包含\函数. inc.php中 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
我认为这是因为LIKE关键字,但我不知道该怎么办。所有表和行的名称都是正确的
我的代码如下所示:

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;
}

有人能给我解释一下为什么会发生这种情况以及如何解决吗?
我尝试将 * 符号更改为我的数据库中更具体的部分-www.example.com,但没有帮助。我尝试使用' %".?." %',但也没有效果。products.id and it didn't help. And I tried using '%".?."%' and it didn't work as well.

t5zmwmid

t5zmwmid1#

这就是问题所在:

$result = mysqli_query($conn, $sql);

mysqli_query()在查询没有查询参数时使用。
如果查询有参数,则仅使用mysqli_prepare()mysqli_stmt_execute()
我建议采取以下顺序:

try {
  $stmt = $conn->prepare($sql);
  $search = "%$search%";
  $stmt->bind_param("ssss", $search, $search, $search, $search);
  $stmt->execute();
  $result = $stmt->get_result();
  $products = $result->fetch_all(MYSQLI_ASSOC);
catch (mysqli_sql_exception $e) {
  error_log($e);
  header("location: ../index.php?error=stmtfailed");
  exit();
}

相关问题