我需要在 while 循环中检查表上是否存在记录。如果没有,我想显示一条消息。根据我所做的代码,如果行存在,它也会输出消息。下面是代码,
<?php
$mysqli = new mysqli("localhost", "root", "", "my_dev");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
die();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM user WHERE staff_id=?"))
{
/* bind parameters for markers */
$stmt->bind_param("i", $id);
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
/* bind result variables */
$stmt->bind_result($t_id, $name, $ic_no);
/* fetch value */
while ($row = $stmt->fetch()) { ?>
<div class="form-group">
<input type="text" name="nama[]" id="nama" class="form-control"
placeholder="Nama" value="<?php echo $name?>" >
</div>
<div class="form-group">
<input type="text" name="ic_no[]" id="ic_no" class="form-control"
placeholder="No. K/P" value="<?php echo $ic_no; ?>" >
</div>
<?php }
if ($row < 1) {
echo "No records!";
}
/* close statement */
$stmt->close();
}
检查病情的正确方法是什么?
你需要问的问题是“什么是$row
?”
让我们逐步执行您的代码,假设上面的所有内容while
都是正确的(我不知道,我不使用 mysqli):
while ($row = $stmt->fetch()) {
只要$stmt->fetch()
返回一个值,在这种情况下很可能是一个对象,$row
接收到该对象,则whle
认为这是真的,并且执行将转到下一行。当$stmt->fetch()
行用完时,它返回false
并while
退出循环。
同时,当你在循环中时,你从数据库中访问数据,通常是通过引用类似的东西 $row->columnName
所以你的 while 循环将是这样的:
while($row = $stmt->fetch()) {
print "I'm column one: " . $row->columnOnesName . "<br>";
print "I'm column two: " . $row->columnTwosName . "<br>";
}
当您用完行时,则$row
获取$stmt->fetch()
给出它的值,这很可能是null
. 这评估为不为真,while 循环中断。
如果你那么做
if ($row < 1) {
如果null
< 1 ,它将跟随分支。
查看是否有任何数据行的一种快速简便的方法是简单地使用一个标志。
$isEmpty = true;
while($row = $stmt->fetch()) {
$isEmpty = false;
// display table's output with $row->columnNames
}
if($isEmpty) {
print "no rows in table";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句