I have a problem with prepare function ==> Call to a member function prepare() on null i have tow pages classo.php and index.php
classo.php :
<?php
class classo
{
function connection(){
$db=new pdo ('mysql:host=localhost;dbname=pronostic','root','');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
}
function insererDonne($pseudo,$password)
{
global $db;
classo::connection();
$donne=array(
'user' =>$pseudo,
'pass' =>$password
);
$req="INSERT INTO users (user,pass) VALUES (:user,:pass)";
$sql=$db->prepare($req);
$sql->execute($donne);
}
}
?>
index.php:
<?php
require('classo.php');
$data=new classo();
$data->insererDonne('dsds','tosdsta');
?>
Do you have an idea as to how I can resolve this? This is the first time I've received this error from PHP and I'm kind of new coding in PHP with objects & classes. Could someone help me fix this problem please?
There are 2 big issues in your code:
- Variable visibility
- Static call
In detail:
In oop you should forget about global variables. They are against the principle of encapsulation. Moreover, you do not even have any global variable in your code, so
global $db;
line is meaningless. Declare a private $db variable on class level (property) initialise it in the connection() method and access it in the insert method.You are calling the connection method as
classo::connection();
. However, you would need to declare connection method as static. Either declare your connection method as static (but then change $db into static as well), or call it as a regular method using $this.
来源:https://stackoverflow.com/questions/37243168/error-in-pdo-call-to-a-member-function-prepare-on-null