PHP while 循环时间
这是我第一次尝试使用面向对象编程。我试图重复数据库中的时间段,但只得到一个结果。
时间段表包含:
10:00:00
10:15:00
10:30:00
在 PHP 类中:
class booking {
function __construct($mysqli) {
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
return $r['times'];
endwhile;
$mysqli->close();
}
}
在网页中显示循环次数:
$booking = new booking($mysqli);
<?php echo $booking->get_timeslot(); ?>
结果:
10:00:00
This is my first time try to use object oriented programming. I'm trying to repeat the timeslot from the database but I'm only getting one result.
timeslot table contains:
10:00:00
10:15:00
10:30:00
in PHP class:
class booking {
function __construct($mysqli) {
}
function get_timeslot() {
global $mysqli;
$q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
return $r['times'];
endwhile;
$mysqli->close();
}
}
in the webpage to showing the looping times:
$booking = new booking($mysqli);
<?php echo $booking->get_timeslot(); ?>
result:
10:00:00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
return 正在返回函数的值,因此您只会收到 1 个返回值。尝试
或
return is returning the value for your function, thus you'll only receive 1 value returned. Try
or
return 语句停止 while 循环继续进行,并退出该函数。您需要修改函数以返回时隙数组,或者修改逻辑以仅期望来自数据库的第一个结果。
the return statement stops the while loop from continuing any further, and exits the function. You'll either need to modify the function to return an array of time slots, or modify your logic to expect only the first result from the database.
return
语句将在调用函数后立即退出该函数。相反,您应该将项目添加到数组中而不是返回整个数组:The
return
statement will exit the function immediately it's called. Instead return you should add the item to array than return the entire array:因为您正在使用 return $r['times'];循环内。
这应该可以解决您的问题:
另一方面,不建议在类方法内或任何地方使用 global 关键字,因为全局作用域允许任何进程访问和更改全局变量。
我建议您尝试使用其他方式访问数据库对象(对象注册表、受保护的属性...)
另外,使用 while 循环的替代语法 (while(): ... endwhile;) 可读性不是很好,但可以对此进行辩论。
Because you are using return $r['times']; inside the loop.
This should solve your problem:
On other note, using global keyword inside a class method or anywhere for that matter i not advisable, since global scope enables any process to access and change global variable.
I would advise you to try using other means of accessing your DB object (object registry, protected property...)
Also using alternative syntax for while loop (while(): ... endwhile;) is not very readable, but one can debate about that.
试试这个:
Try this: