2017-08-29 41 views
0

我有一個測試代碼,我嘗試訪問我的數據庫信息。但是一個使用準備好的語句的腳本不起作用,其次沒有準備好的語句就可以正常工作。無法找到問題出在哪裏:/SELECT不能在PHP中使用變量

$userzzz = "test"; 

有了這個劇本我拿到「BAD」作爲結果

$db = new mysqli("localhost", "root", "", "test"); 
$stmt = $db->prepare('SELECT * FROM user WHERE username=?'); 
$stmt->bind_param('s', $userzzz); 
$stmt->execute(); 
echo $stmt->num_rows(); 
if ($stmt->num_rows > 0){ 
echo "good";  
} else { 
echo "bad"; 
} 

有了這一個,我得到「良好」的結果。

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "test"; 


$conn = new mysqli($servername, $username, $password, $dbname); 

if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT * FROM user WHERE username = '$userzzz'"; 
$result = $conn->query($sql); 

if ($result->num_rows > 0) { 
    // output data of each row 
    while($row = $result->fetch_assoc()) { 
     echo "good"; 
    } 
} else { 
    echo "bad"; 
} 

$conn->close(); 
?> 
+0

'$ username'容器根,你的數據庫連接。不'測試' – aynber

+0

@anyber上帝,這太明顯了。好的,所以第二個可以工作,但使用stmt的仍然不起作用:/ – PhpNewbie

+0

您是否檢查了您的Web服務器的錯誤日誌。你在這裏沒有做任何真正的錯誤檢查。 –

回答

2

在面向對象的mysqli中,num_rows不是函數,它是結果(stmt)的一個屬性。你需要$stmt->num_rows;而不是$stmt->num_rows();

在你的第二個例子中,你沒有使用(),你正在做它,因此它爲什麼在第二個函數,但不是第一個。

$db = new mysqli("localhost", "root", "", "test"); 
$stmt = $db->prepare('SELECT unique_col FROM user WHERE username=?'); 
$stmt->bind_param('s', $userzzz); 
$stmt->execute(); 
$stmt->store_result(); 
$rows = $stmt->num_rows; 
if ($rows > 0){ 
echo "good";  
} else { 
echo "bad"; 
} 

我還添加了$stmt->store_result()。這是finicky和num_rows將爲0,除非您在運行之前存儲結果$stmt->num_rows;

我也會使用一個獨特的列而不是*,例如id例如。

+0

仍然無法正常工作。 – PhpNewbie

+0

上面的語法正確。回顯$行,看看它有什麼 – clearshot66

+0

似乎store_result()解決了這個問題。這很奇怪,因爲我有以前的項目,我沒有使用函數來存儲結果,但它工作得很好。 – PhpNewbie

3

從手動,

採用mysqli_stmt_num_rows()取決於你是否不習慣mysqli_stmt_store_result()緩衝整個結果的語句句柄設置。

如果使用mysqli_stmt_store_result(),則可能立即調用mysqli_stmt_num_rows()

這意味着你必須執行後使用$stmt->store_result();,但訪問num_rows屬性之前。

$stmt = $db->prepare('SELECT * FROM user WHERE username=?'); 
$stmt->bind_param('s', $userzzz); 
$stmt->execute(); 
$stmt->store_result(); 
echo $stmt->num_rows; 
if ($stmt->num_rows > 0){ 
    echo "good";  
} else { 
    echo "bad"; 
} 

如果你不這樣做,該行不會被緩存到內存中,並沒有知道被多少行實際返回的方式,直到您完成整個數據集的環路(由while ($stmt->fetch()))。

0

那麼你需要綁定你執行,這會在你的情況下工作後的結果(爲我的作品):

<?php 
$userzzz = 'test'; 
$db = new mysqli("localhost", "root", "", "test"); 
$stmt = $db->prepare('SELECT * FROM users WHERE username = ?'); 
$stmt->bind_param('s', $userzzz); 
$stmt->execute(); 
$stmt->store_result(); 
echo $stmt->num_rows(); 
if ($stmt->num_rows() > 0){ 
echo "good";  
} else { 
echo "bad"; 
} 
?>