简体   繁体   中英

Class not found

This is the error I am getting.

Fatal error: Class 'Database' not found in C:\\wamp\\www\\midtermexam\\read.php on line 11

<?php
    include 'database.php';
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }

    if ( null==$id ) {
        header("Location: index.php");
    } else {
        $pdo = Database::connect(); //HERE IS THE LINE PROBLEM
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM tbl_students where id = ?";
        $q = $pdo->prepare($sql);
        $q->execute(array($id));
        $data = $q->fetch(PDO::FETCH_ASSOC);
        Database::disconnect();
    }
?>

And here is my database file database.php

<?php 
   $DB_HOST = 'localhost'; 
   $DB_USER = 'root'; 
   $DB_PASS = '';
   $DB_NAME = 'midtermexam'; 
   try{ 
       $DB_con = new PDO("mysql:host={$DB_HOST};
       dbname={$DB_NAME}",$DB_USER,$DB_P‌​ASS); 
       $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
  } 
  catch(PDOException $e){
       echo $e->getMessage(); 
  } ?> 

Try this, I have not tested it but it should be fairly close.

 <?php 
# database.php
#############################
$DB_HOST = 'localhost'; 
$DB_USER = 'root'; 
$DB_PASS = ''; 
$DB_NAME = 'midtermexam'; 
try
{ 
    $DB_con = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}",$DB_USER,$DB_P‌​ASS); 
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} 
catch(PDOException $e)
{ 
    echo $e->getMessage(); 
} 

#############################
?>

<?php
# read.php
#############################
$id = null;
if ( !empty($_GET['id'])) {
  $id = $_REQUEST['id'];
}

if ( null==$id )
{
  header("Location: index.php");
} 
else 
{
  $sql = "SELECT * FROM tbl_students where id = ?";
  $q = $DB_con->prepare($sql);
  $q->execute(array($id));
  $data = $q->fetch(PDO::FETCH_ASSOC);
}

#############################
?>

From what I can tell you are using the name of the database file as the class name, however, you have created the instance of the database connection as $DB_con within the database.php file.

This may help a little for further reading. Sitepoint PDO

If you get any issues with this give us a shout.

Good Luck,

Blinky

step 1: check your database configuation in database.php, make sure that all necessary params have been set and all the values are correct.

step 2: if step 1 can not solve your problem, make sure your database server is running, your network is alive.

that's my view, hope it's useful for you.

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