gpt4 book ai didi

PHP/MySQL - 如果数据库中不存在该行,则包含错误页面

转载 作者:行者123 更新时间:2023-11-29 10:08:05 25 4
gpt4 key购买 nike

如果数据库中不存在行 ID,我会尝试显示错误页面。这是我的代码:

db.php:

 public function getRow()
{
$arr = array();
$get_id = isset($_GET['id']) ? $_GET['id'] : '';
$val_id = intval($get_id);
$rowId = $val_id > 0 ? $val_id : '';
$statement = $this->conn->prepare("SELECT id, username, date, comment from table where id = $rowId");
//echo $this->conn->error;
$statement->bind_result($id, $username, $date, $comment);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "username" => $username, "date" => $date, "comment" => $comment];
}
$statement->close();

return $arr;
}

主要内容:

<?php
require_once("./config/db.php");
$arr = $conn->getRow();
$get_id = isset($_GET['id']) ? $_GET['id'] : '';
$val_id = intval($get_id);
$rowId = $val_id > 0 ? $val_id : '';

for($i=0; $i < count($arr); $i++) {
if ($rowId === $arr[$i]['id'] && $arr[$i]['username'] === $_SESSION['username']) {
$id = $rowId;
$date = $arr[$i]['date'];
$comment = $arr[$i]['comment'];

echo $id;
echo $date;
echo $comment;
} else if ($arr[$i]['id'] = NULL || $arr[$i]['username'] !== $_SESSION['username']) {
include './content/404.php';
}
}
?>

当用户名错误时,我让它显示错误页面,但是当我调用不存在的行ID时,它只返回一个空白页。

如果有人能帮助我发现这里的错误,我将不胜感激。谢谢!

最佳答案

您不需要在循环内检查 id。您已在 getRow() 函数中对其进行了过滤。如果此函数返回一个非空值,则该值肯定包含匹配的 id。

for ($i=0; $i < count($arr); $i++) {
$id = $rowId;
$date = $arr[$i]['date'];
$comment = $arr[$i]['comment'];

echo $id;
echo $date;
echo $comment;
}

if (count($arr) == 0) { // execute if $arr is empty
include './content/404.php';
}

关于PHP/MySQL - 如果数据库中不存在该行,则包含错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51512381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com