Call to undefined method in php - php

Here is my config.php
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'xxxx');
define('DB_USER', 'xxxx');
define('DB_PASS', 'xxxx');
?>
And It is DB.php
<?php
include 'config.php';
class DB {
public static $pdo;
public static function connection(){
if (!isset(self::$pdo)) {
try {
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname ='.DB_NAME,DB_USER, DB_PASS);
}catch(PDOException $e){
echo $e->getMessage();
}
}
return self::$pdo;
}
public static function prepareOwn($sql){
return self::connection()->prepare($sql);
}
}
?>
3rd file is Student.php
<?php
include 'DB.php';
class Student {
public $table = 'student_info';
public function readAll(){
$sql = "SELECT * FROM $this->table";
$stmt = DB::prepareOwn($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
?>
But When I try to access readAll() from index.php using spl_autoload_register() Then I can see Fatal error: Call to undefined method DB::prepareOwn()
Can anyone help me to solve the problem??
Many thanks.
Sahidul

i copied your code into mine and saw your error. but as i guessed, first you will get an error with this line inside db.php:
return self::$pdo->prepare($sql);
Fatal error: Call to a member function prepare() on null
where prepare function came from? $pdo is just a static property in this class and it doesn't have a function called prepare! fix this line
Updated
the problem is you forgot to call connection method inside your prepareOwn. so your new prepareOwn function should be:
public static function prepareOwn($sql) {
self::connection();
return self::$pdo->prepare($sql);
}

i hope this code will work for you
class MySQLDatabase {
// Class attributes
private $host_name = "localhost";
private $database_name = "XXXXXXX";
private $database_username = "XXXXXXX";
private $database_password = "XXXXXXX";
private $is_connected;
private $connection;
private $statement ;
// construct
public function __construct() {
$this->open_connection();
}// End of construct
// connection method
public function open_connection() {
try {
$this->is_connected = TRUE ;
// PDO Connection
$this->connection = new PDO("mysql:host=".$this->host_name.";dbname=".$this->database_name.";charset=utf8",$this->database_username,$this->database_password);
// Error reporting
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE);
} catch(PDOException $errors) {
$this->is_connected = FALSE ;
self::catch_errors($errors);
}
}// End of open connection method
// Get connection method
public function connection(){
return $this->connection ;
}
// Close connection method
public function close_connection() {
$this->connection = null;
}// End of close connection method
private static function catch_errors($errors) {
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
// query method
public function query($sql){
return $this->statement = $this->connection->prepare($sql);
}
}// End of database class
$database = new MySQLDatabase();
class Student {
protected static $table = 'My_table';
public function readAll(){
global $database;
try{
$sql = "SELECT * FROM ". self::$table;
$stmt = $database->query($sql);
$stmt->execute();
return $stmt;
}catch(PDOException $error){
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
}
}
$c = new Student();
$s = $c->readAll();
$stmt = $s->fetchAll(PDO::FETCH_ASSOC);
foreach($s as $v){
var_dump($v);
}

Related

How to call a local property using OOP?

I'm a beginner looking to learn more about PHP OOP, so there are things I don't know, in the ShowUsers() method, I would like to display all users in the database, but I'm not getting it, because I don't know how to call the connection property. If I've been using encapsulation, it would be easy, but I'm using the connection property as local, and I really don't know how to call this property, how can I call it without using encapsulation?
db.php
<?php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
public function __construct() {
try {
$conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
main.php
<?php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = parent::__construct()->prepare($sql); //Problem here
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
Note: I don't want to use encapsulation to make it work, I want to learn how to call the variable without using encapsulation, if possible.
Based on the code above and the comments, I recommend that you declare $conn as protected in your DbConnect class:
<?php
// db.php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
protected $conn;
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
Then in main.php, you can do:
<?php
// main.php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = $this->conn->prepare($sql);
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
?>

Fatal error: Call to a member function prepare() in php oop [duplicate]

This question already has an answer here:
How to use PDO connection in other classes?
(1 answer)
Closed 2 years ago.
Now I learn to create PHP crud operations using OOP concept
In this code I faced some issues
Config.php
<?php
class Database{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "xtratuition";
public $db;
public function __construct(){
if(!isset($this->db)){
try{
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
}
catch(PDOException $e){
die("Failed to connect with MySQL: " . $e->getMessage());
}
return $this->db;
}
}
}
?>
Modules.php
<?php
include_once("config.php");
class CrudController extends Database{
function sqlSelect($TblName , $Condition){
try{
$query = "SELECT * FROM `xtratuition`.$TblName WHERE $Condition";
$result = $this->db->prepare($query);
$result->execute();
$data = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
class LoginController extends CrudController{
public $emailID;
function __construct($email){
$this->emailID = $email;
}
function userLogin(){
$data = $this->sqlSelect("users" , "email = '".$this->emailID."'");
return $data;
}
}
// This is works well
// $login = new CrudController();
// $data = $login->sqlSelect("`users`" , "email = 'klakshmanan48#gmail.com'");
// print_r($data);
$login = new LoginController("klakshmanan48#gmail.com");
$data = $login->userLogin();
print_r($data);
?>
I think I make a mistake in this code.
And I am getting this error
Fatal error: Call to a member function prepare() on null
on this line
$result = $this->db->prepare($query);
If you are defining constructor in child class, you have to call parent constructors explicitly they wont called automatically.
You have to call parent construct in your LoginContoller class
class LoginController extends CrudController{
public $emailID;
function __construct($email){
$this->emailID = $email;
parent::__construct(); //explicit call to parent constructor
}
function userLogin(){
$data = $this->sqlSelect("users" , "email = '".$this->emailID."'");
return $data;
}
}

Fatal error: Call to undefined method ConnectDatabase::query()

i have created an OOP-PHP Script and i get follow Message and i don't understand why???
Fatal error: Call to undefined method ConnectDatabase::query() in .... on line 73
My PHP Code
<?php
class ConnectDatabase {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'database';
private $db_connection;
private $db_query;
//Connect Database.
function __construct() {
$this->open_db();
}
public function query($sql) {
$this->db_query = query($sql, $this->db_connection);
}
public function open_db() {
$this->db_connection = new mysqli($this->host, $this->username, $this->password);
if (is_resource($this->db_connection)) {
die("Error!");
} else {
$this->db_connection->select_db($this->database) or die('Error');
}
}
}
$dbConnection = new ConnectDatabase();
class GetContent {
public function newContent() {
global $dbConnection;
$sql = "SELECT * FROM mytable";
// ----- This Line make an Error ------
$query = $dbConnection->query($sql);
$found = $dbConnection->fetch_array($query);
return $found;
}
}
If you have any Idea please help.

How to use static property and method on database connection class?

Can anyone identify what is wrong with this lines of code? I tried to make db connection a static class so that I can use globally in any class without having to use $this->pdo.
The error shown is:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\carRental\index.php on line 44
<?php
class connection
{
public static $servername = "localhost";
public static $username = "root";
public static $password = "";
public static $dbname = "carrental";
public static $port="3306";
public static $pdo;
public static function addConnection()
{
try {
self::$pdo = new PDO("mysql:host=self::$servername;port=self::$port;dbname=self::$dbname", self::$username, self::$password);
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
self::$pdo->query("use self::$dbname");
return self::$pdo;
}
}
class car
{
public $name;
public $maker;
public $type;
public $colour;
public $passanger;
public function __construct($param1,$param2,$param3,$param4,$param5)
{
$this->name=$param1;
$this->maker=$param2;
$this->type=$param3;
$this->colour=$param4;
$this->passanger=$param5;
}
public function addCar()
{
$sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
echo "Data inserted!";
}
}
$car1=new car("Honda Accord","Honda","5 wheeler","Red",9);
$car1->addCar();
?>
As #Rizier123 already said in the comment, you didn't call addConnection(). So, you might need to do this, inside the addCar() method of class car
$sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";
$pdo_obj = connection::addConnection(); //get the pdo object
$stmt = $pdo_obj->prepare($sql);
$stmt->execute();
echo "Data inserted!";

OOP using php and mysqli to return data from database

I have a Database php file and a user php file. The Database is where I make my connection to the database.
<?php
/*
* Mysqli database class - only one connection
*/
class Database{
private $_connection;
private static $_instance; //The single instance
private $_host = 'localhost';
private $_username = 'root';
private $_password = '';
private $_database = 'blogwebsite';
public static function getInstance(){
if(!self::$_instance){ // If no instance make one
self::$_instance = new self();
}
return self::$_instance;
}
/*
* Constructor
*/
public function __construct(){
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()){
trigger_error("Failed to connect to MySQL: " .
mysqli_connect_errno(), E_USER_ERROR);
}else{
echo "You are connected to " . $this->_database;
}
}
// Magic method clone is empty to prevent duplication of connection
public function __clone(){ }
// Get mysqli connection
public function getConnection(){
return $this->_connection;
}
}
?>
This is the user page and I am including the Database page. I get an error that is saying ' Undefined variable: mysqli' AND 'Call to a member function prepare() on a non-object'.
<?php
include('class.database.php');
class api{
public function __construct(){
$db = Database::getInstance();
$mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username);
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
$username = new api();
echo $username->getUsername($username);
?>
Can anyone please help with any assistance. Thank you verry much.
You don't have a 'mysqli' variable in class 'api'. Also, you should call getConnection() after getting the Database instance.
class api{
private $mysqli;
public function __construct(){
$db = Database::getInstance()->getConnection();
$this->mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $this->mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username);
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
You need to create a local variable $mysql :
class api{
protected $mysql; // <-- Here
public function __construct(){
$db = Database::getInstance();
$this->mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $this->mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username); // <-- what this for ?
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
$username = new api();
echo $username->getUsername($username);

Categories