Fatal error: Call to a member function prepare() on null
It looks like your $pdo
variable is not initialized.
I can't see in the code you've uploaded where you are initializing it.
Make sure you create a new PDO object in the global scope
before calling the class methods. (You should declare it in the global scope because of how you implemented the methods inside the Category class).
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
PHP PDO - Uncaught Error: Call to a member function prepare() on null
Because of the scope of the function call you need to pass in the connection to the function. First, setup the function call to receive the connection:
function getAddress($conn)
$conn
here is just a convenient name for the variable which will use what you have in place inside the function. Passing the connection to the function is the preferred method of making a connection available in a function. The global
keyword should be avoided.
Now, call the function with your established connection variable:
echo getAddress($conn);
$conn
here is the successful connection from your included file. This will put the connection into the scope of your function and your query should be successful if all else is equal.
How to fix Fatal error: Call to a member function prepare() on null in
1) Your problem with creating connection and creating database.
Cuz You define:
$af_cbms_database="af_cbms";
and then You call:
$dbh->query("CREATE DATABASE IF NOT EXISTS $af_database");
so where in Your code You've defined $af_database
variable?
2) it's too unprofessional to make this (seems like You're new to programming):
$af_cbms_database = "`" . str_replace("`", "``", $af_cbms_database) . "`";
You've already defined Your variable and then replacing it, funny, like You don't trust Yourself that You've defined variable? (:
or You cannot do it like this? :
$dbh->query("CREATE DATABASE IF NOT EXISTS `".$af_cbms_database."`");
$dbh->query("USE `".$af_cbms_database."`");
3) Don't complicate Your code wit too much of variables like $af_
, be simple as in this fixed code of dbconnect.php
:
<?php
global $dbh;
$host = "localhost";
$user = "root";
$password = "";
$db_name = "af_cbms";
try {
$dbh = new PDO("mysql:host=$host", $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->query("CREATE DATABASE IF NOT EXISTS ".$db_name);
$dbh->query("SET CHARACTER SET utf8");
$dbh->query("USE ".$db_name);
}
catch(PDOException $e) {
die($e->getMessage());
}
4) BONUS: Don't use global $dbh
, because may happen that some process, some code can replace $dbh
variable. Also using global
vars is not in fashion (:
so have some Object that will keep shared stuff :
class Objs {
private $data = [];
final public static function set($key, $instance, $preventReset = false) {
if($preventReset === true AND isset(self::$data[$key])) {
return self::$data[$key];
}
return self::$data[$key] = $instance;
}
final public static function get($key, $instance) {
return self::$data[$key];
}
}
and in Your db connection file:
require_once('classes/Objs.php');
Objs::set('db', $dbh, true);
and in Your another files:
$stmt = Objs::get('db')->prepare('SELECT * FROM city_tbl');
Fatal error: Uncaught Error: Call to a member function prepare()
You are accidentally using a variable variable.
See this demo:
<?php
class myclass {
public $foo = 'foo';
public $bar = 'bar';
function __construct() {
}
function myfunc($foo) {
echo "foo = {$this->foo}\n";
echo "bar = {$this->bar}\n";
echo "variable '$foo' = {$this->$foo}\n";
}
}
$m = new myclass();
$m->myfunc('foo');
$m->myfunc('bar');
$m->myfunc('baz');
Output:
foo = foo
bar = bar
variable 'foo' = foo
foo = foo
bar = bar
variable 'bar' = bar
foo = foo
bar = bar
PHP Warning: Undefined property: myclass::$baz in p.php on line 13
Warning: Undefined property: myclass::$baz in p.php on line 13
variable 'baz' =
Conclusion: When you reference a class member variable, don't use the second $
if you want to reference the variable directly. Only use the second $
if you want to use a variable variable. That is, the name of the member variable is in a string variable.
Uncaught Error: Call to a member function prepare() on null error
You just have somes mistakes in your code. Try to use this lines :
Connection file :
<?php
class Connection {
public $dbh;
// Setting Database Source Name (DSN)
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=employees';
// Setting options
$options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
// Making the connection to the database
try {
$this->dbh = new PDO($dsn, 'root', '', $options);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
}
$connection = new connection();
users.php file :
<?php
include 'connection.php';
class Users {
public $name;
public $surname;
public $employmentDate;
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
if(isset($_POST['Submit'])) {
$this->name = $_POST['name'];
$this->surname = $_POST['surname'];
$this->employmentDate = $_POST['employmentDate'];
}
}
// Inserting users values to the database table
public function insertUserValues() {
$query = 'INSERT INTO employee (name,surname,employment_date) VALUES (:name,:surname,:employmentDate)';
$stmt = $this->connection->dbh->prepare($query);
$stmt->bindValue(':name',$this->name, PDO::PARAM_STR);
$stmt->bindValue(':surname',$this->surname, PDO::PARAM_STR);
$stmt->bindValue(':employmentDate',$this->employmentDate, PDO::PARAM_STR);
$stmt->execute();
}
}
$users = new Users($connection);
$users->insertUserValues();
Explanations :
- You have to pass the $connection variable to your users class (or import it with
global $connection;
) - Your connection file has to make visible the dbh property, otherwise you will not be able to make any query on your database
- PDO prepare() method is waiting for a query in first argument
- You don't need to pass an array to execute() method if you already have binded your values before
PDO - Fatal error: Call to a member function prepare() on null
you're using: $query = $pdo->prepare
It should be:
$query = $conn->prepare()
Because I am a lazy coder I made a new class to save a bit of time:
class DBCommon
{
private $conn;
/** @var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Fatal error: Call to a member function prepare() on null in on line 28
You may need to remove spaces here: mysql:host = localhost; dbname=cms4.2.1
would be mysql:host=localhost;dbname=cms4.2.1
Also, wrap the connecting statement in a try-catch block to see if you connect correctly.
try {
$DSN = 'mysql:host=localhost;dbname=cms4.2.1';
$ConnectingDB = new PDO($DSN, 'root', '');
$ConnectingDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
}
catch(PDOException $e){
echo $e->getMessage();
}
PHP Fatal error: Call to a member function prepare()
You set the connection
property of your class to NULL
in the catch
block inside DBconnection::dbConnect()
with $this->connection = NULL;
. Yet, in your other functions you do not check for that. By not throwing an error for that you make it an accepted state within your class.
Your solution would be:
- Do not catch the exception from your database connection in the class, but catch it upon initializing an instance of it instead and handle it accordingly. Like this
DBconnection->connection = NULL
would become an illegal state in your class and you could ignore that case in your other methods.
Example:
try {
$con = new DBTransaction();
$result = $con->select_all('SELECT * FROM table');
} catch (Exception $e) {
$result = NULL;
}
- Hande the state, that
DBconnection->connection
might beNULL
in your other methods and return and approriate value for that case:
Example:
public function select_all($query) {
if (this->connection === NULL) {
return NULL;
}
$result = $this->connection->query($query);
$result->execute();
return $result;
}
Related Topics
Convert Timestamp to Readable Date/Time PHP
Using PHP'S Swiftmailer With Gmail
Export MySQL Data to Excel in PHP
PHP Password_Hash(), Password_Verify()
How to Detect Strings Like Putjbtghguhjjjanika
Persistent/Keepalive Http With the PHP Curl Library
How to Remove a Variable from a PHP Session Array
Yii2 Htaccess - How to Hide Frontend/Web and Backend/Web Completely
How to Get the Real Url After File_Get_Contents If Redirection Happens
Get Difference Between Associative Rows of Two 2-Dimensional Arrays