简体   繁体   中英

Getting undefined variable: pdo in index.php

I am creating a recipe's database and after adding 'add' and 'delete' functionality, the system throws an error:

Notice: Undefined variable: pdo in C:\xampp\htdocs\COMP1321\recipes\index.php on line 52 Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\COMP1321\recipes\index.php:52 Stack trace: #0 {main} thrown in C:\xampp\htdocs\COMP1321\recipes\index.php on line 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();
}

I have been trying to solve this problem for 3 hours already. Some help would be appreciated!

Full 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';

Looks like you never include the database connection file.

If $_POST['recipename'] is not set, and $_GET['deleterecipe'] is not set, then when you get to that line, db.inc.php has never been included, so $pdo is not defined.

You need to move your include 'admin/includes/db.inc.php'; line to be right below the form.html.php include.

This will make it available for the entire page as it is required regardless of whether or not you are inserting or deleting a recipe since you need it for the selection block at the bottom.

You only need to include the file once per page and I would normally use require_once() at the top of the file for the DB and other global dependencies like this, rather than trying to include it each place you need it 3+ times per file and then end up unnecessarily including the file and possibly generating warnings or errors. Generally it just makes your code more complicated. It's a shared resource, let it be shared. Or create a singleton to creates or retrieve the PDO instance for you in a standard way so you only have 1 PDO connection instead of potentially multiple per request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM