[英]How to Show message if no results returned from db query in php
想知道是否有人可以提供帮助。 我正在运行有关php和mysql的教程,其中有一个笑话数据库,其中包含:
我有一个名为authors.html.php的页面,其中包含作者列表,并提供添加作者,编辑/删除作者的选项(每个返回作者的名字旁边)。 我想做的是,如果包含作者的数据库为空,而不显示以下php错误:
注意:未定义的变量:第22行的C:\\ wamp \\ www \\ chapter7 \\ admin \\ authors \\ authors.html.php中的作者
我想显示一个整洁的消息,说没有找到结果。
我的代码如下:
<?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"];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.