MySQL中的MySQLi准备好的声明无法正常工作

时间:2016-09-18 10:56:54

标签: php mysqli prepared-statement

我试图从MySQL中的一个表中拉出一个字段,并在php中准备一个语句,但我一直得到一个空的结果。我知道场地在桌子上,但没有任何东西被拉。这是我的代码:

if (!($stmt = $conn->prepare("SELECT password from members WHERE username = \"Bill\""))) 
{
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}


if (!$stmt->bind_result($result)){
    echo "Bind failed";
}

 $sql_searched_password = $result;
  echo $sql_searched_password." 

2 个答案:

答案 0 :(得分:2)

您忘记调用->fetch()这是将数据从结果集中提取到绑定变量的命令。

您还可以使查询更容易阅读并进行调试,特别是当查询变得更复杂时,在双引号字符串文字中使用单引号

if (!($stmt = $conn->prepare("SELECT password from members WHERE username = 'Bill'"))) 
{
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}


if (!$stmt->bind_result($result)){
    echo "Bind failed";
}

$stmt->fetch();

echo $result;

事实上,准备一个查询是为了让你可以在准备之后将参数传递给它,并且可能因此你可以使用不同的参数多次调用预准备语句。

所以这可能是一个更好的例子

if (!($stmt = $conn->prepare("SELECT password from members WHERE username = ?"))) 
{
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}

if (!$stmt->bind_param("s", 'Bill')) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}

if (!$stmt->bind_result($result)){
    echo "Bind failed";
}

$stmt->fetch();
echo $result;

// bind a new value to the existing prepared query
if (!$stmt->bind_param("s", 'William')) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $conn->errno . ") " . $conn->error;
}

if (!$stmt->bind_result($result)){
    echo "Bind failed";
}

$stmt->fetch();

echo $result;

答案 1 :(得分:1)

致电$stmt->bind_result($result)表示

  

结果将绑定到$result变量。

请参阅 - will be bindedbind_result不从db中获取您的行。使用fetch

获取行
$stmt->bind_result($result);

while ($stmt->fetch()) {
    $sql_searched_password = $result;
}

echo $sql_searched_password;

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

请参阅manual