首页 > 解决方案 > 获取未定义的变量: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';

标签: phpmysqlpdo

解决方案


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

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


推荐阅读