将查询转换为预准备语句

时间:2014-09-11 15:08:59

标签: php mysql sql prepared-statement

在没有运气的情况下尝试了几个小时。

我们有这个查询

$commercial_name = strip_tags($_POST['commercial_beer']);    
$q = "SELECT bb_comm_id FROM bb_commercial WHERE bb_comm_name = '" . $commercial_name . "'";    
$r = @mysqli_query ($dbc, $q); // Run the query.
$row = @mysqli_fetch_array ($r, MYSQLI_ASSOC);
$comm_id = $row['bb_comm_id'];

哪个工作正常。我正在尝试使用准备好的语句并想出了这个

$commercial_name = strip_tags($_POST['commercial_beer']);   
$q = "SELECT bb_comm_id FROM bb_commercial WHERE bb_comm_name = ?"; 
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $commercial_name);
$r = mysqli_stmt_execute($stmt);
$row = @mysqli_fetch_array ($r, MYSQLI_ASSOC);
$comm_id = $row['bb_comm_id'];

哪个不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:1)

由于不太清楚您的问题是什么,我将分享用于调试数据库查询的代码。我甚至会把它缩减到你的代码中。

$commercial_name = strip_tags($_POST['commercial_beer']);
if($stmt=$dbc->prepare("SELECT bb_comm_id FROM bb_commercial WHERE bb_comm_name = ?")){
    if (!$stmt->bind_param("s", $commercial_name)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field()) {
        $parameters[] = &$row[$field->name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $parameters);
    while ($stmt->fetch()) {
        foreach($row as $key => $val) {
            $x[$key] = $val;
        }
        $comm_id[] = $x;
    }
    $stmt->close();
}else{
    echo "Prepare failed: (" . $dbc->errno . ") " . $dbc->error;
}

此代码将报告每一步是否发生错误,并将结果集中的所有行保存在$comm_id内。

尝试并告诉我你是否还有问题。

另外我认为$commercial_name之前的字符应该是"s"而不是"i",因为它是一个字符串,大概不是整数。

更多'生产就绪'版本:

$stmt=$dbc->prepare("SELECT bb_comm_id FROM bb_commercial WHERE bb_comm_name = ?");
    $stmt->bind_param("s", $commercial_name);
    $stmt->execute();
    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field()) {
        $parameters[] = &$row[$field->name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $parameters);
    while ($stmt->fetch()) {
        foreach($row as $key => $val) {
            $x[$key] = $val;
        }
        $comm_id[] = $x;
    }
$stmt->close();

之后你可以从$ comm_id中获取行,例如,第一个结果将存储在$comm_id[0]["bb_comm_id"]

或者如果你只想要一行作为答案:

$stmt=$con->prepare("SELECT bb_comm_id FROM bb_commercial WHERE bb_comm_name = ?");
$stmt->bind_param("s", $commercial_name);
$stmt->execute();
$stmt->bind_result($comm_id);
$stmt->fetch();
$stmt->close();