简单搜索功能,MySQL编写语句问题

时间:2014-04-14 15:57:23

标签: php mysql mysqli

我目前正在为网站创建一个非常简单的搜索功能,用户可以使用多种不同的标准(从一个到多个不同的数字)在数据库中搜索事件。我在准备好的声明中遇到了问题,我特别使用了bind_param()。

以下是相关的PHP代码:

...
...
$title = (empty($_POST['eventTitle'])) ? null : $_POST['eventTitle'];
$venue = (empty($_POST['venue'])) ? null : $_POST['venue'];
$catID = (empty($_POST['catID'])) ? null : $_POST['catID'];
$start = (empty($_POST['start'])) ? null : $_POST['start'];
$end = (empty($_POST['end'])) ? null : $_POST['end'];
$price = (empty($_POST['price'])) ? null : $_POST['price'];

include 'database_conn.php';

$sql = 'SELECT eventID, eventTitle, venueID, catID, eventStartDate, 
eventEndDate, eventPrice FROM te_events WHERE 1';

$sqlCondition = '';

$bindFirstArg = '"';
$bindSecondArg = '';

if($title !== null && !empty($title)) {

    $sqlCondition = $sqlCondition . " AND eventTitle LIKE \"%" 
    . $title . "%\"";

}

if($venue !== null && $venue !== '0') {

    $sqlCondition = $sqlCondition . " AND venueID=?";
    $bindFirstArg = $bindFirstArg . "s";
    $bindSecondArg = $bindSecondArg . ", " . $venue;

}

if($catID !== null && $catID !== '0') {

    $sqlCondition = $sqlCondition . " AND catID=?";
    $bindFirstArg = $bindFirstArg . "s";
    $bindSecondArg = $bindSecondArg . ", " . $catID;

}

if($start !== null && $start !== '0') {

    $sqlCondition = $sqlCondition . " AND eventStartDate=?";
    $bindFirstArg = $bindFirstArg . "s";
    $bindSecondArg = $bindSecondArg . ", " . $start;

}

if($end !== null && $end !== '0') {

    $sqlCondition = $sqlCondition . " AND eventEndDate=?";
    $bindFirstArg = $bindFirstArg . "s";
    $bindSecondArg = $bindSecondArg . ", " . $end;

}

if($price !== null && !empty($price)) {

    $sqlCondition = $sqlCondition . " AND eventPrice=?";
    $bindFirstArg = $bindFirstArg . "i";
    $bindSecondArg = $bindSecondArg . ", " . $price;

}

$sql = $sql . $sqlCondition;
$bindFirstArg = $bindFirstArg . '"';

$search_stmt = $conn -> prepare($sql);

if (false===$search_stmt) {

    die('prepare() failed: ' . htmlspecialchars($conn->error));

}


$search_stmt -> bind_param($bindFirstArg, $bindSecondArg);
$search_stmt -> execute();
$search_stmt -> bind_result($eventIDRes, $eventTitleRes, $venueIDRes, 
$catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);

while ($search_stmt->fetch()) {

    printf ("%s %s %s %s %s %s %i\n", $eventIDRes, $eventTitleRes, 
    $venueIDRes, $catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);

}

mysqli_stmt_close($search_stmt);

错误我接收状态

  

警告:mysqli_stmt :: bind_param()[mysqli-stmt.bind-param]:类型定义字符串中的元素数量与/var/www/vhosts/numyspace.co中的绑定变量数量不匹配。第101行和第34行的英国/ web_users / home / ~unn_w12019212 / public_html / webdev / searchresult.php;

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要在查询中为每个 bind_param传递? 单独的参数,并将格式作为第一个参数。你不能将逗号分隔的字符串传递给它,但它不会起作用。它只是将其视为第一个?,然后抱怨你没有发送它。

另外,请勿在{{1​​}}字符串中添加引号。 $bindFirstArg只需要所有数据类型的列表(bind_paramids),它不需要{{ 1}}字符。

您需要做的是将您的值推送到数组中,然后通过b致电"

bind_param