[英]fetch() won't work inside a while loop
I'm working on my collage project and a problem just came up. 我正在做我的拼贴项目,结果出现了问题。 I want to make a while loop to fetch all the records from the database.
我想进行一个while循环以从数据库中获取所有记录。
The code that I use for my SQL statement: 我用于SQL语句的代码:
$sql2 = "SELECT * FROM phones WHERE users_id = '$user_id'";
$stm2 = $db->prepare($sql2);
$stm2->execute();
The code that I use for the while loop: 我用于while循环的代码:
<?php while ($record = $stm2->fetch()) :?>
<div class="col-md-2">
Some text
</div>
<?php endwhile; ?>
This loop hasn't got output. 该循环没有输出。 Nothing shows up when I run the project.
当我运行项目时,什么都没有显示。
If I try to fetch all the records first and then var_dump them out, it's okay. 如果我尝试先获取所有记录,然后将它们var_dump取出,那就可以了。 I mean that I can see that there are records in the database, but I can't do use these records inside the loop.
我的意思是,我可以看到数据库中有记录,但是我无法在循环中使用这些记录。
I've tried this code too and nothing came out again. 我也尝试过此代码,但没有任何结果。
<?php while($record = $stm2->fetch()){
echo '<div class="col-md-2">';
echo 'Some text';
echo '</div>';
}
To get it to work the way you seem to be intending, you should do it this way: 要使其按照您的预期方式工作,您应该采用以下方式:
First, select the exact columns you want. 首先,选择所需的确切列。
Second, use ? 二,使用 as placeholder for security.
作为安全的占位符。
Third, prepare, then bind your parameters in to your query. 第三,准备,然后将参数绑定到查询中。 i for integers, s for strings.
i代表整数,s代表字符串。
Execute, then run a while on the fetch. 执行,然后在获取时运行一段时间。
<?php
$sql2 = "SELECT col1,col2,col3 FROM phones WHERE users_id = ?";
$stm2 = $db->prepare($sql2);
$stmt2->bind_param("i",$user_id);
$stm2->execute();
$stmt->bind_result($col1,$col2,$col3);
while($stmt2->fetch()){
echo "<div class='col-md-2'>";
echo $col1; // echo each iteration out, works just like $result->fetch_assoc()
echo $col2; // equivalent of $row['col2']; but in prepared statement style because you're binding the rows
echo $col1." plus ".$col2;
echo "</div>";
}
$stm2->close(); // close stmt
$db->close(); // close connection
?>
Try this: 尝试这个:
$query = "SELECT * FROM phones WHERE users_id = '$user_id'";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["FirstName"], $row["LastName"], ...);
}
/* free result set */
$result->free();
}
EDIT 编辑
This is just a quick and dirty example... you should indeed use prepare statements as suggested in the comment 这只是一个快速而肮脏的示例……您确实应该按照注释中的建议使用prepare语句
EDIT 2 编辑2
Remove the , ...
from this line: printf ("%s (%s)\\n", $row["FirstName"], $row["LastName"], ...);
从此行中删除
, ...
: printf ("%s (%s)\\n", $row["FirstName"], $row["LastName"], ...);
if you don't have any other columns to output from the database 如果没有其他要从数据库输出的列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.