在index.php中获取未定义变量:pdo



我正在创建一个食谱的数据库,在添加'添加'和'删除'功能后,系统抛出一个错误:

注意:未定义变量:pdo在C:xampphtdocsCOMP1321recipesindex.php第52行在C:xampphtdocsCOMP1321recipesindex.php:52堆栈跟踪:#0 {main}抛出在C:xampphtdocsCOMP1321recipesindex.php第52行

index . php

try // selection block
{
$sql = 'SELECT * FROM recipe';
$result = $pdo->query($sql);
} 

Databaseconnection.inc.php

<?php
try
{
//new PDO('mysql:host=mysql.cms.gre.ac.uk; dbname=mdb_', '', '');
$pdo = new PDO('mysql:host=localhost; dbname=mdb_recipes', 'root', ''); 
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
} catch (PDOException $e) {
$error = 'Unable to connect to database server';
include 'error.html.php';
exit();
}

我已经试着解决这个问题3个小时了。如果能得到一些帮助,我将不胜感激!全index . php

<?php
if(isset($_GET['addrecipe'])) {
include 'form.html.php';
exit();
}
//insert block
if (isset($_POST['recipename'])) {
include 'admin/includes/db.inc.php';
try
{
//prepared statement
$sql = 'INSERT INTO recipe SET
recipename = :recipename,
recipedate = CURDATE()';
$s = $pdo->prepare($sql);
$s->bindValue(':recipename', $_POST['recipename']);
$s->execute();
} catch (PDOException $e) {
$error = 'Error adding submitted recipe' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
//delete block
if(isset($_GET['deleterecipe']))
{
include '../includes/db.inc.php';
try
{
$sql = 'DELETE FROM recipe WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error deleting recipe' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
try // selection block
{
$sql = 'SELECT * FROM recipe';
$result = $pdo->query($sql);
} 
catch (PDOException $e) {
$error = 'Error fetching recipes' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row) {
$recipes[] = array(
'id' => $row['id'],
'recipename' => $row['recipename'],
'time' => $row['time'],
'ingredients' => $row['ingredients'],
'recipetext' => $row['recipetext'],
'servings' => $row['servings'],
'nutritionfacts' => $row['nutritionfacts'],
'recipedate' => $row['recipedate'],
'image' => $row['image'],
);
}
include 'recipes.html.php';

看起来您从未包含数据库连接文件。

如果没有设置$_POST['recipename'],并且没有设置$_GET['deleterecipe'],那么当您到达该行时,db.inc.php从未包含,因此$pdo未定义。

您需要将include 'admin/includes/db.inc.php';行移动到form.html.php include.

这将使它可用于整个页面,因为它是必需的,无论你是否插入或删除一个食谱,因为你需要它在底部的选择块

你只需要每页包含一次文件,我通常会在DB和其他全局依赖关系的文件顶部使用require_once(),而不是试图在每个地方包含它,你需要每个文件3+次,然后最终不必要地包括文件,并可能产生警告或错误。通常它只会让你的代码更复杂。这是一个共享的资源,让它被共享。或者创建一个单例,以标准的方式为您创建或检索PDO实例,这样您就只有一个PDO连接,而不是每个请求可能有多个PDO连接。

最新更新