简体   繁体   中英

Prepared SQL LIKE statement not returning all results

I have a function to search my ingredient DB (error reporting removed for clarity):

    $servername = "localhost";
    $username = "root";
    $password = "*****";
    $dbname = "addb_db";

    $query = "%" . $_POST["query"] ."%";

    $conn = new mysqli($servername, $username, $password, $dbname);

    $sql = "SELECT id, name FROM addb_ingredients WHERE name LIKE ? or id like ?";
    $stmt = $conn -> prepare($sql)
    $stmt->bind_param('ss', $query,$query)
    $stmt->execute()
    $stmt->bind_result($id,$name)
    while ($stmt->fetch()) {
        $ing_array[] = array($id,$name);
    }
    $response_array["status"] = "success";
    $response_array["data"] = $ing_array;

    echo json_encode($response_array);


    $stmt->close();
    $conn->close();

This only returns partial results for particular queries, eg for "bi", these are the results returned:

  • Bison Grass Flavored Vodka
  • Bitter
  • Bitter Lemon
  • Bitters
  • Celery Bitters
  • Chilled hibiscus tea
  • Chocolate Bitters
  • Orange Bitters
  • Peach Bitters
  • Peychaud's bitters
  • Wasabi Paste

Running this query on phpMyAdmin returns the same, as it should.

However, when entering "bit", the results from the php above are:

  • Bitter Lemon
  • Bitters
  • Celery Bitters
  • Chocolate Bitters
  • Orange Bitters
  • Peach Bitters
  • Peychaud's bitters

Whereas the results should be:

在此处输入图片说明

The 'bitter' result is excluded and I can't work out why.

I'm not particularly strong with PHP, but I've noticed that 'Bitter' would have been the first result if using '%bit%' as a parameter. Likewise, 'Absolut Hibiskus' should be the first result when using '%bi%' as a parameter.

My guess is that the first result is consumed within this block of code without actually being assigned anywhere within $ing_array :

$stmt->bind_result($id,$name)
while ($stmt->fetch()) {
    $ing_array[] = array($id,$name);
}

Quite indicative, there are no screenshots for the actual output provided. Means the OP is judging their prepared statement output by distant indirect consequences. Like some processing on the client side.

There are no errors neither in prepared statements nor in LIKE statement responsible for such a behavior. 100% of reported errors of the same kind were caused by the userland code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM