php - 获取未定义的变量:index.php 中的 pdo
问题描述
我正在创建食谱的数据库,在添加“添加”和“删除”功能后,系统会抛出错误:
注意:未定义的变量:第 52 行 C:\xampp\htdocs\COMP1321\recipes\index.php 中的 pdo 致命错误:未捕获的错误:在 C:\xampp\htdocs\COMP1321\ 中调用 null 上的成员函数 query() recipes\index.php:52 堆栈跟踪:#0 {main} 在第 52 行的 C:\xampp\htdocs\COMP1321\recipes\index.php 中抛出
索引.php
try // selection block
{
$sql = 'SELECT * FROM recipe';
$result = $pdo->query($sql);
}
数据库连接.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 个小时了。一些帮助将不胜感激!
完整索引.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
未定义。
推荐阅读
- docker - 找不到配置选项的 docker 卷
- swift - 我可以在枚举中使用委托吗?(迅速)
- python - 从字符串python中提取年龄
- tensorboard - 什么是 hp.Discrete 和 hp.Realinterval?我可以在 hp.realinterval 中包含更多值而不仅仅是 2 吗?
- c# - 用 linq 替换两个 foreach 循环
- symfony - 来自常量的 Symfony 多路由需求
- windows - 将 CMAKE_SYSTEM_NAME 设置为 Generic 后,CMAKE_INSTALL_PREFIX 未添加到 CMAKE_SYSTEM_PREFIX_PATH
- node.js - NodeJS Mongoose 将事件插入到 public/index.html
- c# - 在 .net core 3.0 上运行集成服务 SSIS
- spring-boot - Spring Boot 应用程序不会将日志写入 Wildfly 14 上的日志文件