簡體   English   中英

php 中為 MySQLi 准備的語句不起作用

[英]Prepared statement for MySQLi in php not working

我正在嘗試使用 php 中的准備好的語句從 MySQLi 中的表中提取一個字段,但我一直得到一個空結果。 我知道該字段在表中,但沒有任何內容被拉出。 這是我的代碼:

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." 

調用$stmt->bind_result($result)意味着

結果將綁定到$result變量。

看—— will be binded bind_result不會從數據庫中獲取您的行。 使用fetch獲取行:

$stmt->bind_result($result);

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

echo $sql_searched_password;

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

請參閱手冊

您忘記調用->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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM