Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\xampp\htdocs\blog\system\functions.php on line 31

Tags:

php

Getting a couple of errors and can't for the life of me see where I am falling down. Below is the functions file

<?php
include('config.php');

function getAllPosts()
{
    try {
        $dbh = new PDO(DB_HOST, DB_USER, DB_PASS);
    } catch (PDOException $e) {
        echo $e->getMessage();
    }

    $stmt = $dbh->prepare('SELECT id, title, content FROM posts ORDER BY created_at DESC');
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $results;
}

function getSinglePost($id)
{
    try {
        $dbh = new PDO(DB_HOST, DB_USER, DB_PASS);
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
    $stmt = $dbh->prepare('SELECT title, content FROM posts WHERE id = ?');
    $bindings = array($id);
    $stmt->execute($bindings);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result;
}

?>

Also figured I should include the page that I am running to generate the error

<?php include('system/functions.php'); ?>
<html>
<head>
<title>Create A New Post | My First Blog</title>

<link rel="stylesheet" type="text/css" href="style.css">

</head>

<body>
<div id="form">
<?php if (isset($_GET['id'])){ ?>

<h2>Single Post:</h2>

<?php $post = getSinglePost($_GET['id']); ?>
<?php print_r($post); ?>

<?php } ?>
<fieldset>
</fieldset>
</div>

</body>
</html>

Any help much appreciated these are the errors in full.

Notice: Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\xampp\htdocs\blog\system\functions.php on line 31

Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in C:\xampp\htdocs\blog\system\functions.php on line 31

Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in C:\xampp\htdocs\blog\system\functions.php on line 31 invalid data source name Notice: Undefined variable: dbh in C:\xampp\htdocs\blog\system\functions.php on line 37

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\blog\system\functions.php on line 37

Should include config file too

<?php
define('DB_HOST','mysql:host=localhost;dbname=blog');
define('DB_USER','root');
define('DB_PASS','');
?>
like image 934
BrogenMacy Avatar asked Jan 25 '13 13:01

BrogenMacy


2 Answers

The constants you are using for Host, User and Password haven't been defined yet. There's probably something wrong with your config.php.

like image 146
Louis Huppenbauer Avatar answered Sep 28 '22 09:09

Louis Huppenbauer


that means DB_HOST is not defined or DB_HOST is not accessible in the current context.

Try place these varibles in the script at the begining instead of include('config.php');

define('DB_HOST','mysql:host=localhost;dbname=blog');
define('DB_USER','root');
define('DB_PASS','');
like image 42
Techie Avatar answered Sep 28 '22 08:09

Techie