想知道是否有人可以帮助。我通过PHP和MySQL的教程运行,那里是持有一个笑话数据库:如何显示消息,如果没有结果返回数据库查询在PHP
- 笑话的笑话表
- 作者在作者表中类别表
- 分类
我有一个名为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();
}
请注意我非常新的这个和已经尝试了一些反复失败的悲惨,所以任何帮助,甚至只是简单的指导,将步骤我通过思考围绕创建这样的功能将不胜感激。不只是寻找正确的答案,而是想要了解如果任何人都可以提供帮助的背后的想法会很棒。
*“我有一个名为'authors.html.php'的页面,其中包含作者列表”* - 并且您正在执行'include'authors.html.php';'?我不明白。对我来说,似乎是一个无尽的循环。 – 2014-09-05 12:34:12
if(sizeof($ result)== 0){// code here no results} else {// foreach ...} – Jack 2014-09-05 12:36:41
你应该遵循一个更好的教程。 – 2014-09-05 12:40:30