I am new to OOP, so I am trying to learn how to create classes and use them. Currently I am trying to fetch data from my MySQL table.
To create the connection with MySQL I am using PDO. I have created a separate class for database connection. I have included the class in my show.php file. Now I want to fetch data from MySQL database. The problem is when I run my show.php file it shows this error message
Fatal error: Call to undefined method DBConnection::prepare() in C:\xampp\htdocs\jm\show.php on line 10`
But it was supposed to display just array.
What is the solution to this problem?
File db.class.php
<?php
class DBConnection {
function DBConnection(){
$host = 'localhost';
$dbname = 'srijon';
$user = 'root';
$pass = '';
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
} // function ends
} // class ends
?>
File show.php
<?php
require_once 'db.class.php';
function get_all(){
$db = new DBConnection();
$sql = "SELECT * FROM information";
$STH = $db->prepare($sql);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
return $STH;
}
echo get_all();
?>
DBConnectionclass doesn't have a method calledprepare(). If you want to usePDO's prepare you would have to extend it. But you really have to ask yourself: "do I really need to wrap the PDO class"?__construct(). Also you're trying to make your constructor return somethingreturn $DBH. That doesn't work. The constructor return an instance of the class.get_all()function without having to give the database connection information. Could you please edit my code and show me how exactly to write the code to achieve this? Thanks :)