您好我有以下代码,如果数据库中没有行,我尝试计算num行以显示消息。我有一个数组,我已经使用foreach循环数组值并查询数据库。问题是,如果数组中的一个ID返回0行但另一个返回一行,我从数据库查询中获取值,但也会收到没有找到行的消息。有人知道为什么吗?非常感谢
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if ($numTicket < 1) {
echo "no rows found";
}
答案 0 :(得分:2)
您在循环内更新的循环之后检查变量$numTicket
。
如果最后$numTicket
为0,您将陷入最后的状态。
您可以尝试这样的事情:
$have_tickets = false ;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
$have_tickets = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$have_tickets) {
echo "no rows found";
}
答案 1 :(得分:0)
每次循环时,您都要为$numTicket
赋值。这意味着当您在循环之后到达if
语句时,它将包含循环内分配给它的 last 值。你想要做的是使用一个标志来确定通过循环的任何迭代是否产生计数/结果。
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
// initialize the flag to false
$ticketsFound = false;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
// flip the flag to true since tickets were found
$ticketsFound = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$ticketsFound) {
echo "no rows found";
}