简体   繁体   English

为什么fetch_assoc()不返回值?

[英]Why is fetch_assoc() not returning a value?

For the life of me I can't figure out why fetch_assoc() is returning false here: 对于我一生,我无法弄清楚为什么fetch_assoc()在这里返回false:

$username = $_POST['username'];
print("Username is " . $username . "<br>");

//Create query
$query = ("SELECT * FROM users WHERE username = '" . $username . "'");
print($query . "<br>");

//Run query
if (!$result = $db2 -> query($query)) {
    print("Query failed!");
}

if (!$user = new LG_User($result))
    print("Failed to create user!<br>");

while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
var_dump($rows);
print("User is " . $user -> first_name . "<br>");

The query is successful and the new user object is created, because the last line of code is printing $user->first_name correctly. 查询成功并创建了新的用户对象,因为最后一行代码正确打印了$ user-> first_name。 I'm using the very same block of code to populate the $rows array on another page and it is working. 我正在使用相同的代码块在另一页上填充$ rows数组,并且该数组正在运行。 What am I doing wrong here? 我在这里做错了什么? If I try to use 如果我尝试使用

while($row = mysqli_fetch_assoc($result)) { $rows[] = $row; }

instead of 代替

while($row = $result -> fetch_assoc()) { $rows[] = $row; }

it still doesn't work. 它仍然不起作用。 What am I missing here? 我在这里想念什么?

You haven't shown the code for the LG_User constructor, but if it's filling in $user from the database, it must be calling a fetch function itself. 您尚未显示LG_User构造函数的代码,但是如果它是从数据库中填充$user ,则它本身必须在调用fetch函数。 So when it returns, all the rows of the result have been fetched, and there's nothing left for your loop to read. 因此,当它返回时,结果的所有行都已被获取,并且没有任何内容可供循环读取。

You can go back to the beginning of the result set with the data_seek method. 您可以使用data_seek方法返回结果集的data_seek

if (!$user = new LG_User($result))
    print("Failed to create user!<br>");
$result->data_seek(0);
while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
var_dump($rows);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM