SQL LIKE query failing - fatal error in prepared statement

后端 未结 4 705
天涯浪人
天涯浪人 2021-01-15 20:32

I have the following code:

$countQuery = \"SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE \'% ? %\'\";
if ($numRecords = $con->prepare($countQuer         


        
相关标签:
4条回答
  • 2021-01-15 20:47

    Have you issued

    mysqli_free_result($result);
    

    after the last query? That's the command out of sync error.

    This should work however

    $countQuery = "SELECT ARTICLE_NO FROM AUCTIONS1 WHERE upper(ARTICLE_NAME) LIKE ?";
    if ($numRecords = $con->prepare($countQuery)) {
        $numRecords->bind_param("s", "%".$query."%");
    

    Wondering what is in the $query variable. Try doing this instead

    $query = '%'.$query.'%';
    $numRecords->bind_param("s", $query);
    
    0 讨论(0)
  • 2021-01-15 20:48

    For LIKE clause, use this:

    SELECT ARTICLE_NO FROM AUCTIONS1 WHERE upper(ARTICLE_NAME) LIKE CONCAT('%', ?, '%')
    

    As for the table name, it's an extremely bad practice to have table names as parameters.

    If for some reason you still need to do it, you'll need to embed it into the query text before preparing the query:

    $countQuery = "SELECT ARTICLE_NO FROM $table_name WHERE upper(ARTICLE_NAME) LIKE CONCAT('%', ? ,'%')";
    if ($numRecords = $con->prepare($countQuery)) {
        $numRecords->bind_param("s", $brand);
        $numRecords->execute();
        $data = $con->query($countQuery) or die(print_r($con->error));
        $rowcount = mysql_num_rows($data);
        $rows = getRowsByArticleSearch($query, $table, $max);
        $last = ceil($rowcount/$page_rows);
    }
    
    0 讨论(0)
  • 2021-01-15 20:49

    Try the following instead:

    $countQuery = "SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE ?";
    if ($numRecords = $con->prepare($countQuery)) {
        $numRecords->bind_param("ss", $table, "%$brand%");
        $numRecords->execute();
        $data = $con->query($countQuery) or die(print_r($con->error));
        $rowcount = mysql_num_rows($data);
        $rows = getRowsByArticleSearch($query, $table, $max);
        $last = ceil($rowcount/$page_rows);
    }
    
    0 讨论(0)
  • 2021-01-15 21:02

    Afaik you can't use placeholders for identifiers with mysqli and prepare statements. So you'd have to manually interpolate the tablename into the query.

    0 讨论(0)
提交回复
热议问题