0

Hello i have a question PDO connection. My conn.php is

<?php
define('host', 'localhost');
define('host_user', 'root');
define('host_pass', '');
define('host_db', 'testdb');
class Database {
public $conn;
public function Connect() {
try {
$conn = new PDO("mysql:host=" . host . ";dbname=" . host_db, host_user, host_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection error:" . $e->getMessage();
}
}
}
?>

When i use this

$dbClass = new Database();
$stmt = $dbClass::Connect()->prepare("SELECT * FROM user_posts");

it returns following error:

Call to a member function prepare() on null

Why is it happen?

Nikhil Vaghela
  • 2,088
  • 2
  • 15
  • 30
user3227899
  • 65
  • 2
  • 9

1 Answers1

1

You get an error because prepare() is a function of PDO, but since Connect() doesn't return anything, you're calling prepare() on nothing.

You hsould modify Connect() so that it returns the PDO object. Add this at the end of the function (or the end of the Try block):

return $conn;
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165