gpt4 book ai didi

php - 如果php中的数据库查询没有返回结果,如何显示消息

转载 作者:行者123 更新时间:2023-11-29 23:50:24 26 4
gpt4 key购买 nike

想知道是否有人可以提供帮助。我正在运行有关 php 和 mysql 的教程,其中有一个笑话数据库,其中包含:

  • 笑话表中的笑话
  • 作者表中的作者
  • 类别表中的类别

我有一个名为authors.html.php 的页面,其中包含作者列表,其中包含添加作者、编辑/删除作者的选项(位于每个返回作者的姓名旁边)。我想做的是,如果包含作者的数据库为空,而不是显示以下 php 错误:

Notice: Undefined variable: authors in C:\wamp\www\chapter7\admin\authors\authors.html.php on line 22

我想显示一条简洁的消息,表示未找到结果。

我的代码如下:

<?php   
include $_SERVER['DOCUMENT_ROOT'] . '/chapter7/includes/db.inc.php';
try {
$result = $pdo->query('SELECT id, name FROM author');
} catch (PDOException $e) {
$error = 'Error fetching authors from the database!';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}

foreach ($result as $row){
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}

include 'authors.html.php';

if (isset($_POST['action']) and $_POST['action'] == 'Delete') {
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/includes/db.inc.php';
//Get jokes belonging to author
try {
$sql = 'SELECT id FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error ='Error getting list of jokes to delete.';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
$result = $s->fetchAll();
//Delete joke category entries
try {
$sql = 'DELETE FROM jokecategory WHERE jokeid =:id';
$s = $pdo->prepare($sql);
//For each joke
foreach ($result as $row) {
$jokeId= $row['id'];
$s->bindValue(':id', $jokeId);
$s->execute();
}
} catch (PDOException $e) {
$error = 'Error deleting category entries for joke.';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
//Delete jokes belonging to author
try {
$sql = 'DELETE FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error = 'Error deleting jokes for author';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
//Delete the author
try {
$sql = 'DELETE FROM author WHERE id =:id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error ='Error deleting author';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
header('Location: .');
exit();
}

请注意,我对此非常陌生,并且已经尝试过一些惨败的迭代,因此任何帮助,甚至只是简单的指导,可以引导我思考创建此类功能,我将不胜感激。不仅仅是寻找正确的答案,而是想了解背后的想法,如果有人可以提供帮助,那就太好了。

最佳答案

类似的东西应该可以工作。我过去用过这个,它对我很有用。您将需要调整查询等以适应您的数据库和表,但这应该没问题。

$stm = $PdoObj->prepare("SELECT * FROM NEWS_articles");
$stm ->execute();
$results = $stm ->fetchAll();

if($results==null){
echo "<p>No dice, try other criteria</p>";
}else{
foreach($results as $row){
echo $row["articleName"];
}
}

关于php - 如果php中的数据库查询没有返回结果,如何显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685980/

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