$stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->store_result();
//if SELECT statement returns 1, grab data.
if ($stmt->num_rows === 1) {
echo "Got Row";
$result = $stmt->get_result();
var_dump($result);
while ($row = $result->fetch_assoc()) {
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
}
这真的很奇怪,查询必须经过,因为脚本回显“Got Row”,到目前为止我没有错误。但是当我尝试使用$ result-> fetch_assoc()时出现错误,$ result吐出错误,为什么会这样?请原谅这个问题看起来多么愚蠢,我还在学习如何使用mysqli。 :)
答案 0 :(得分:1)
您的问题既不愚蠢也不奇怪。 store_result()
和get_result()
会让您感到困惑。
这两个函数均从数据库中获取整个记录集。提取数据后,您将无法再次获取数据。因此,您不能同时使用这两个功能!
我们可以通过两种方式修复您的代码。
使用store_result()
:
$stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->store_result();
//if SELECT statement returns 1, grab data.
if ($stmt->num_rows === 1) {
echo "Got Row";
$stmt->bind_result($username, $email, $password);
while ($stmt->fetch()) {
// use the data here
var_dump($username);
}
}
与get_result()
:
$stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$result = $stmt->get_result();
//if SELECT statement returns 1, grab data.
if ($result->num_rows === 1) { // <--- !!! We are using the result object here
echo "Got Row";
foreach ($result as $row) {
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
}
}