Trying to get property of non-object php error [duplicate] - php

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Call to a member function on a non-object - works localhost but not online
don't know how to solve this problem, it's basic but can't find a solution.
I use two files: connect.php and user.php.
in connect.php is a Connect class:
class Connect{
var $logged;
function login($username, $password){
..more code..
if($pass==$password){
$this->logged=true; // db connection is fine, this works
// checked it with echo $this->logged;
}
}
}
and when i call it from another file, user.php like this:
$user=new Connect;
$user->login();
echo $user->logged; // ERROR Trying to get property of non-object
Why is this code not working, but it works offline (locally)???

You've got a couple of problems:
When you call $user->login, PHP is assuming you're accessing an object property, not the function; you need $user->login() (note the ()), which will call the method.
Your example is missing a }.
Demo:
<?php
class Connect{
var $logged;
function login($username, $password){
$pass = 'test';
if($pass == $password){
$this->logged = true;
}
}
}
$user = new Connect;
$user->login('test','test');
print_r($user);
?>
http://codepad.org/AVw0k9sY
Outputs:
Connect Object
(
[logged] => 1
)
1 is what true prints.

To access a class property from outside the class, you need to declare it as 'public':
class Connect{
public $logged;

Related

Call to a member function prepare() on a non-object in (non object) [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I get this error: Call to a member function prepare() on a non-object in line 25.
I have marked the line 25 that it's referring to; can someone please check and tell what's wrong? I tried all possible ways, but can't figure it out.
class db
class db {
public $connect;
private $username = "root";
private $password = "";
private $dns="mysql:host=localhost;dbname=etrharam_db";
private $method=array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set name utf8");
public function connection(){
$connect= new PDO($this->dns,$this->username,$this->password,$this->method);
return $connect;
}/*connection*/
public function Idu($query,$data){
$pre=$this->connect->prepare($query);
foreach($data as $index=>$val){
$pre->bindValue($index+1,$val);
}
$pre->execute();
}/*idu*/
public function Select($query,$data){
$pre=$this->connect->prepare($query);
foreach($data as $index=>$val){
$pre->bindValue($index+1,$val);
}
$pre->execute();
$res=$pre->fetchAll(PDO::FETCH_ASSOC);
return $res;
}/*select*/
}/*db*/
test.php
include ('oop.php');
$oop= new db;
$query="SELECT * FROM `newcoll_tbl` WHERE id=?";
$data=array('1');
$res=$oop->Select($query,$data);
print_r($res);
what is the problem?
Thank you in advance.
Your variable $connect is empty because it's never filled. Your function connection is never called, that's why your getting this error.
To fix this, you can do two things:
Call $oop->connection();
Change name of function connection to __construct so it runs automatically when calling $oop= new db();
I would recommend the second option

PDO database connection can not be used in other classes, but others can? [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
I've been working on a databaseHandler php class, which should connect to the database and then be usable in other PHP files, atleast this was the plan. I've come across the problem that it cannot use any PDO related functions in my PHP class, i've tried checking if it was null, or not set at all (but it was) and i've also tried using a dummy function that just echos something which was to test if the class isn't undefined in others.
<?php
class databaseHandler {
private $db;
private static $instance;
function __construct() {
$this->buildDatabaseConnection();
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new databaseHandler();
}
return self::$instance;
}
private function buildDatabaseConnection() {
require 'dbconfig.php';
try {
$this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE . ";charset=utf8", USER, PASSWORD);
if(isset($this->db)) {
if(!is_null($this->db)) {
echo "isn't null";
}
}
} catch(PDOException $e) {
$e->getMessage();
}
}
public function getConnection() {
return $this->$db;
}
public function getSomeShit() {
echo "some shit";
}
}
?>
The problem might be with the getConnection() php function, does it actually return the PDO object here? Because the main problem lays with the fact that i get this error when i use my getConnection function in other classes:
Notice: Undefined variable: database in F:\Websites\DevProject\php\functions.php on line 69
Fatal error: Uncaught Error: Call to a member function prepare() on null in F:\Websites\DevProject\php\functions.php:69 Stack trace: #0 F:\Websites\DevProject\php\functions.php(51): register('qwe', 'sdasd', 'asdasd', 'asdas', '01-01-1970') #1 F:\Websites\DevProject\register.php(123): datelessRegister('qwe', 'sdasd', 'asdasd', 'asdas') #2 {main} thrown in F:\Websites\DevProject\php\functions.php on line 69
and line 69 would be this:
$stmnt = $database->prepare("SELECT $username, $email FROM " . USERTABLE);
Where the $database variable is the class instance:
$database = databaseHandler::getInstance();
If i try to var_dump it in my registration php file, it'll tell me this:
object(databaseHandler)#1 (1) { ["db":"databaseHandler":private]=> object(PDO)#2 (0) { } }
However, when i use it inside of my function, it will say it is 'NULL', why is it null in a function but defined globally?
All the errors relate to the object, and in there it tells me the pdo is undefined (i've tried checking if it was null, but it wasn't!)
Any help would be great, thanks in advance.
In the return statement of getConnection method you should write the class variable without $:
return $this->db;
Also, you must do the queries on the PDO connection instead of your database handler class, so $database = databaseHandler::getInstance(); should be
$database = databaseHandler::getInstance()->getConnection();
or you can simply use the __call magic method to keep your code as it is right now:
public function __call($method, $args)
{
return call_user_func_array(array($this->db, $method), $args);
}
Also, to clarify how to use this class, you should call it inside every method you need the database to be used, not only once on the top of your file, because defining it there it will not be available inside your methods/functions unless you don't use the global statement to import the variable. However usage of the global variable is not encouraged and it is considered as a bad practice. An example on how to use the database would be:
public function doSomething()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
public function doSomethingElse()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
If you know there are many methods inside your class that uses the database then you can define it as a class variable and set the db instance in the constructor.
You seem to be having issues with scopes.
$database = databaseHandler::getInstance();
function doSomething()
{
// $database is not defined in this scope
$database->getConnection()->prepare(/* ... */);
}
You have to declare it as part of the global scope
function doSomething()
{
global $database;
$database->getConnection()->prepare(/* ... */);
}
The problem seems to be in the getConnection() function. Since $db is field you must do.
return $this->db;
However this is a very complex class structure for a simple problem.
You can directly extend your class from PDO
class DatabaseHandler extends PDO {
function __construct() {
parent::__construct('mysql:host=host_name;dbname=db_name', 'user_name', 'password');
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
And create an object of this whenever you want to do database transaction.
$db = new DatabaseHandler();
$stmt = $db->prepare(".....");
$stmt->execute();

PHP - Call To Undefined Method

I have a PHP class with a few functions defined, this class is responsible for database access:
class database {
function open($params) {
// code here to open the db
}
function close() {
// code here to close the db
}
function count_users() {
// code here counts the number of user records
// Return -1 for testing
return -1;
}
function insert_user($user) {
// code here inserts a user record
}
function select_user($user_id) {
// code here selects a user record
}
}
I have accessor classes defined as follows:
require_once("database.php");
class user {
public $user_id;
public $email_address;
// etc, etc
}
class db_user {
static function select_user($user_id) {
$db = new database();
$db->open();
$user = NULL;
$result = $db->select_user($user_id);
// Test the result and decode user record into $user, etc
$db->close();
return $user;
}
static function count_users() {
$db = new database();
$db->open();
$count = $db->count_users();
$db->close();
return $count;
}
}
My issue occurs when I attempt to count the number of users through db_user::count_users(); which always fails with a Fatal Error: call to undefined method database::count_users
If I dump the database class methods using get_class_methods, I can see that the count_users function isn't present in the list but I have no idea why.
I'm very much a PHP n00b so there maybe something really obvious I'm not doing. My db_user and user classes have many other functions which pull data back through the database class and all of these succeed - just this one function.
Please help!
UPDATE
Ok, so, having removed a couple of functions from the database class and re-uploaded the file to the live server, it appears that it is somehow being "cached" as when I dump the methods belonging to the database object, the removed methods are still displayed in the list.
The count_users function is also not present in the method list yet when I inspect the file uploaded to the server, it is there in code.
Is there any way of removing this caching???
Try as follows:
class user extends database {
//code user class goes here
}
or
class user extends db_user {
//code user class goes here
}
simple problem solved.
You can store you instance of Database to the variable.
class db_user {
public static $db;
static function openDatabase(){
self::$db = new database();
self::$db->open();
}
static function select_user($user_id) {
$user = NULL;
$result = self::$db->select_user($user_id);
// Test the result and decode user record into $user, etc
self::$db->close();
return $user;
}
static function count_users() {
$count = $db->count_users();
self::$db->close();
return $count;
}
}
The issue, it would appear, is related to another version of the "database.php" file hiding in a sub-folder which must have been copied there by mistake.
Having removed this troublesome file, all now works as expected.
Thanks for your help.
Tried running your code in on-line phptester tool - first complained about missing $params in $db->open(), removing the argument (or passing the $params) it works fine on php 5.2,5.3,5.4. No complaints about count_users().

Fatal error: Call to a member function get_row()

I'm working for admin login please anybody fix that..
Email: <?php echo $admin->get_email(); ?>
Fatal error: Call to a member function get_row() on a non-object in D:\MyWebSite\business_design\admin\admin-class.php on line 82
The code:
public function get_email() {
$username = $_SESSION['admin_login'];
global $db;
$info = $db->get_row("SELECT `email` FROM `user` WHERE `username` = '" . $db->escape($username) . "'");
if(is_object($info))
return $info->email;
else
return '';
}
Okay, are you using a framework?
Your $db variable is not instantiated, so when you call $db->get_row:
PHP can't find the $db object; and so,
get_row() can't exist.
To start with, make sure you know which class $db should be referring to. The same class will have the function "get_row"
First you have to include that class file in your php scrip file. That can be done easily by following script -
function __autoload($class_name){
require_once("RELATIVE_ADDRESS_OF_THE_CLASS".$class_name.".php");
}
Say for example you have your class is Database, so you should first instantiate $db as below -
$db = new Database();
Later if all the scripts are working properly in "Database" class, it should work straightaway...
Hope it helps..

Trouble connecting to the database

I'm trying to connect to 2 databases. One of them is a remote database. Once i connected to the remote database i had trouble with the one that existed, it gave me 'supplied argument is not valid ' on mysql_fetch_array() . So i changed my database class a bit and tried to make it work. But i still get errors :(. Its not grabbing $connection variable.
i get "undefined variable connection".
this is my connection class. Please help me out. Appreciate your help.
global $connection;
class Database{
function __construct()
{
$this->open_connection();
}
public function open_connection()
{
$connection = $this->connection= mysql_connect(SERVER,UNAME,PASSWORD);
if(!$this->connection)
{
return false;
}
if(!mysql_select_db(DB_NAME,$this->connection))
{
return false;
}
return true;
}
public function close_connection()
{
mysql_close($this->connection);
}
//open_connection();
}
$database = new Database();
and in another page:
$result=mysql_query($query,$connection);
while ($rec = mysql_fetch_array($result)) ... etc
p.s all constants and other variables are correct.
Using a global variable in a class is like death.
You could provide a class field for the connection link
$this->connection = mysql_connect(...);
And outside your class
$result = mysql_query($sql, $object->connection);
I'd also suggest you to use the existing mysqli class.
Hmm... Well, it looks like you are getting an undefined error thrown because you are calling global $connection at the top of the class file, and it hasn't been assigned a value.
It looks like you are establishing $connection inside of the open_connection() method... Are you establishing $connection in some included file that you haven't mentioned?
Try removing the first line of code, perhaps?
the "global $connection;" MUST be inside "open_connection" method or use #peipst9lker method

Categories