使用php绑定sql选择查询的结果


Binding the results of an sql select query using php

在下面的代码中,"$_POST['search']"是由用户输入到表单中的。如果数据库中的有效主键与他们的搜索匹配,将显示表中的一行。我需要能够访问实际的主键在我的程序中的另一个用途。由于某些原因,下面的代码没有在$col变量中存储任何内容。

 $stmt2 = mysqli_prepare($link, "SELECT * from classes WHERE course_id LIKE ?");
 mysqli_stmt_bind_param($stmt2,'s', $_POST['search']);
 mysqli_execute($stmt2);
 mysqli_stmt_bind_result($stmt2, $col1, $col2, $col3, $col4, $col5, $col6);
 mysqli_stmt_fetch($stmt2);
 echo "<h1>This should be primary key: " . $col1 . "</h1>";

编辑:多亏了David,上面的代码现在是正确的,但是解决方案在接下来的行中直接导致了错误。以下是错误信息:

警告:mysqli_fetch_field()期望参数1为mysqli_result,布尔值

警告:mysqli_fetch_array()期望参数1为mysqli_result,布尔值

$result = mysqli_stmt_get_result($stmt2);
echo "<br><br><table>";
while($row = mysqli_fetch_field($result)){
    echo "<th>'n";
    echo $row->name . "<br>";
    echo "</th>'n";
}
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
    echo "<tr>";
    foreach($row as $value){
         echo "<td>";
         echo $value . "<br>";
         echo "</td>'n";
 }

您已经将变量绑定到结果,但还没有从结果中获取记录。看一下文档示例。更像这样:

mysqli_stmt_bind_result($stmt2, $col1, $col2, $col3, $col4, $col5, $col6);
while (mysqli_stmt_fetch($stmt2)) {
    echo "<h1>This should be primary key: " . $col1 . "</h1>";
}

即使您只需要结果中的第一条记录,您仍然需要获取该记录:

mysqli_stmt_bind_result($stmt2, $col1, $col2, $col3, $col4, $col5, $col6);
mysqli_stmt_fetch($stmt2);
echo "<h1>This should be primary key: " . $col1 . "</h1>";