douhuan1257 2015-01-22 17:58
浏览 92

PHP MySQL预处理语句 - 使用包含撇号的LIKE搜索不起作用

I have a problem with a query with MySQL using prepared statement with PHP. Here is the explanation, step-by-step (remove prenthesis, there are here to focus on the search term).

  1. I have a website with a search box. A user type in it (hiver) without the parenthesis. The results give something good, it finds: (Brassin d'hiver).

  2. The user then search again with the word (d'hiver), nothing is found.

  3. The user then search again with ('hiver) and the search gives (Brassin d'hiver) correctly.

So it seems like there is a problem when an apostrophe is used in the search. I go in my code to look for any problems. Here is the function called when a search is triggered:

<?php
/**
 * Function to search within all Beers names.
 * @return array $theBeers All Beers information in an array.
 */
function searchBeers($SEARCHQUERY)
{
    $SEARCHQUERY = "%".$SEARCHQUERY."%";

    $theBeers = array();

    // Connect to Database
    $this->connect();

    /* create a prepared statement */
    if($stmt = $this->link->prepare("SELECT id, name FROM `beers` WHERE `beers`.`name` LIKE ? ORDER BY name ASC"))
    {
        /* bind parameters for markers */
        $stmt->bind_param('s', $SEARCHQUERY);

        /* execute query */
        $stmt->execute();

        /* bind variables to prepared statement */
        $stmt->bind_result($col1, $col2);

        /* fetch values */
        $i = 0;
        while($stmt->fetch())
        {
            $theBeers[$i]['id'] = $col1;
            $theBeers[$i]['name'] = $col2;

            $i++;
        }

        /* close statement */
        $stmt->close();

        return $theBeers;
    }   
    return false;
}
?>

If I am using the phpMyAdmin GUI, I am able to easily fix this problem by adding double quotes around the searchquery: "%searchquery%". But using prepared statement, I am unable to do it. There is this ? that I have no idea what to do with it.

Note: Any other kind of search without an apostrophe wors perfectly.

Let me know if you guys want a link directly to the search to test it.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 Revit2020下载问题
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数