maybe this is a possible duplicate, i have search here some questions like this but i have tried all the answers, but i still got this error
Notice: Undefined property: User::$_pdo in D:\xampp\htdocs\pengun\classes\DB.php on line 32
and this error
Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\pengun\classes\DB.php on line 32
this is my DB class
<?php
class DB {
private $_pdo, $_query, $_result, $_count, $_row;
public function __construct($host, $dbname, $user, $password) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
try {
$_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
} catch (PDOException $e) {
die($e->getMessage());
}
$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function select($fields, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=','>','<','>=','<=');
$column = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "SELECT {$fields} FROM {$table} WHERE {$column} {$operator} {$value}";
if($this->_query = $this->_pdo->prepare($sql)) {
$this->_query->execute();
$this->_row = $this->_query->fetch();
print_r($this->_row);
}
}
}
}
}
can someone please tell me what is the problem with my code? thanks in advance.
Because in constructor, you are assigning new PDO just to local variable accessible only inside constructor. You have to use:
$this->_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
...
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
You are assigned PDO object to local variable in constructor. You must set class variable!
Change
$_pdo
to
$this->_pdo
in lines 13 and 18.
Related
I'm getting another error with this code. It's:
Connected successfully
Fatal error: Uncaught Error: Call to a member function query() on null in index5.php:29 Stack trace: #0 index5.php(44): User->getAllUsers() #1 index5.php(55): ViewUser->showAllUsers() #2 {main} thrown in index5.php on line 29
I'm trying to echo out data from my database table called "indeximg" but this code gives me the error above. I'm not sure how to fix this. This is my code:
<?php
class Database {
private $host = 'localhost';
private $db_name = 'photos';
private $username = 'root';
private $password = '';
private $conn;
protected function connect() {
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
$this->conn = null;
}
}
class User extends Database {
protected function getAllUsers() {
$sql = "SELECT * FROM indeximg";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if ($numRows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
}
}
class ViewUser extends User {
public function showAllUsers() {
$datas = $this->getAllUsers();
foreach ($datas as $data) {
echo $data['id']."<br>";
echo $data['username']."<br>";
}
}
}
$users = new ViewUser();
$users->showAllUsers();
?>
query() method called from null because you are returning nothing from the connect() function. Add a line as shown in the comment.
protected function connect() {
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
return $this->conn;//Add this line
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
$this->conn = null;
}
There are a couple of issues in your connect() function:
First, you are setting $this->conn as null even when it connects successfully.
Second, you are chaining a function to the result of the connect() function that doesn't return anything:
protected function connect()
{
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die('Connection Error: ' . $e->getMessage()); // Or do something else to handle the error
}
return $this->conn;
}
I am learning php oop with mysql and I am having trouble fixing this code.
I have checked it twice and also checked this platform to confirm.
<?php
require 'databasesclass.php';
$database = new Database();
$database->query('SELECT * FROM users');
$rows = $database->resultset();
print_r($rows);
and my data base class are
<?php
class Database{
private $host = 'localhost:8889';
private $user = 'root';
private $pass = 'root';
private $dbname = 'register';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set the DSN
$dsn = 'mysql:host='. $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
// set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($pram, $value, $type = null){
if (is_null($type)){
switch(true) {
case is_int($value):
$type = PDO::PRAM_INT;
break;
case is_bool($value):
$type = PDO::PRAM_BOOL;
break;
case is_null($value):
$type = PDO::PRAM_NULL;
break;
default:
$type = PDO::PRAM_STR;
}
}
$this->stmt->bindValue($parm, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchALL(PDO::FETCH_ASSOC);
}
}
Fatal error: Uncaught Error: Call to a member function prepare() on
null in C:\MAMP\htdocs\Practice\databasesclass.php:31 Stack trace: #0
C:\MAMP\htdocs\Practice\index.php(7): Database->query('SELECT * FROM
u...') #1 {main} thrown in C:\MAMP\htdocs\Practice\databasesclass.php
on line 31
And the Line 31 is:
$this->stmt = $this->dbh->prepare($query);
No need to pass $this->user and $this->pass into your $dns variable. Remove them from there.
So $dns variable will be
from
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
to
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
Please check and let me if you see any error there.
In the moment that you are executing the $database->query('SELECT * FROM users') the $this->dbh is null. You could check if it is an instance of PDO before do the prepare.
This question already has answers here:
pdo - Call to a member function prepare() on a non-object [duplicate]
(8 answers)
Closed 6 years ago.
i am getting error : Fatal error: Using $this when not in object context in line $stmt_edit = $this->conn->prepare('SELECT userName, userEmail, phone FROM tbl_users WHERE userID =:uid'); , i followed this , this
& this and all other google , yahoo links but nothing worked for me, please check below code and help me.
usr
global $DB_con;
error_reporting( ~E_NOTICE );
require_once 'dbconfig.php';
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $this->conn->prepare('SELECT userName, userEmail, phone FROM tbl_users WHERE userID =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: home.php");
}
dbconfig
<?php
$db = isset($_POST['db']) ? $_POST['db'] : '';
class Database
{
private $host = "localhost";
private $db_name = "designer3";
private $username = "root";
private $password = "123456";
public $conn;
public function dbConnection()
{
global $DB_con;
$db = isset($_POST['db']) ? $_POST['db'] : '';
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
update
i tried by creating new object un user page, but still it did't worked for me : gave this strange error : Fatal error: Call to a member function prepa‌​re() on a non-object in
code
$oDb=new Database();
$custDb=$oDb->dbConnection();
$custDb->conn->prepare('SELECT userName, userEmail, phone FROM tbl_users WHERE userID =:uid');
Your code should be
global $DB_con;
error_reporting( ~E_NOTICE );
require_once 'dbconfig.php';
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
$id = $_GET['edit_id'];
$stmt_edit = $DB_con->conn->prepare('SELECT userName, userEmail, phone FROM tbl_users WHERE userID =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: home.php");
}
$this reference to the current object, it's most commonly used in object oriented code.
Reference: http://www.php.net/manual/en/language.oop5.basic.php
Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
and your dbconfig.php should be
<?php
$db = isset($_POST['db']) ? $_POST['db'] : '';
class Database
{
private $host = "localhost";
private $db_name = "designer3";
private $username = "root";
private $password = "123456";
public $conn;
public function dbConnection()
{
global $DB_con;
$db = isset($_POST['db']) ? $_POST['db'] : '';
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
$DB_con=$this->conn;
return $this->conn;
}
}
?>
I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}
i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks