local server vs server server

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wibblywobbly
Forum Newbie
Posts: 17
Joined: Mon Oct 19, 2009 10:11 am

local server vs server server

Post by wibblywobbly »

Hi Everyone,

I'm running an Authentication class that works perfectly on my local server, MAMP. When I upload it I get an error, and I'm not sure why...

The error is:
Fatal error: Call to a member function query() on a non-object in /home/myusername/public_html/classes/Authenticate.php on line 28.
Line 28 of the Authentication class reads:

Code: Select all

$result = $this->db->connection->query($sql);
Perhaps I need to offer some more code for you to be able to give me any advice, but, why would something work on my local server and not on my actual server?

Very frustrating, I'm quite proud of getting this code to work and now it doesn't :(

Let me know if you can give me any advice, it would be greatly appreciated.

-- wibblywobbly.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: local server vs server server

Post by Eran »

The error basically means that connection is not an object. From what you describe I can assume that connecting to the database on the remote server is failing, likely due to incorrect credentials (a guess).
Perhaps I need to offer some more code
Show us the connection code and MySQL errors messages
wibblywobbly
Forum Newbie
Posts: 17
Joined: Mon Oct 19, 2009 10:11 am

Re: local server vs server server

Post by wibblywobbly »

I think I am getting to to the bottom of this.

The problem is my server doesn't support the mysqli() function and my Class DB.php is built around that. So as a start to solving this I need to build a new connect to database function, without mysqli. I'm trying to do so with mysql_connect() and mysql_select_db() instead.

I'm still getting to grips with OOP so I'll show you what I'm trying to do:

Here is the class (that works when your server has mysqli)

Code: Select all

<?php
 
//this class will establish a db connection using the mysqli driver
 
class DB{
 
    public $connection;
 
    public function __construct()
    {
        $this->connect();
    }
    
    public function Connect()
    {
        try{
            //connect to db, the variables here come from a config.php file.
            $this->connection = new mysqli(SERVER,DB_USER,DB_PWD,DB_NAME);
 
            //check for connection error
            if(mysqli_connect_error())
                throw new Exception(mysqli_connect_error());
            else
            return $this->connection;
 
        }catch(Exception $e){
            echo("Connection failed, try again later" . $e->getMessage());
        }
    }
}
 
?>
 
So I've begun to add in the older functions, mysql_connect() and mysql_select_db(), but I've got really lost. Any advice would be brilliant!

Here we go...

Code: Select all

<?php
 
//this class will establish a db connection WITHOUT the mysqli driver
 
class DB{
 
    public $connection;
 
    public function __construct()
    {
        $this->connect();
    }
    
    public function Connect()
    {
        try{
            //connect to db
            $this->connection = new mysql_connect(SERVER,DB_USER,DB_PWD);
            
            //concatenate something like this on the end of the string?
            $this->connection = new mysql_select_db(DB_NAME);
 
            //check for connection error
            if(mysql_error())
                throw new Exception(mysql_error());
            else
            return $this->connection;
 
        }catch(Exception $e){
            echo("Connection failed, try again later" . $e->getMessage());
        }
    }
}
 
?>
lshaw
Forum Commoner
Posts: 69
Joined: Mon Apr 20, 2009 3:40 pm
Location: United Kingdom

Re: local server vs server server

Post by lshaw »

Code: Select all

 
class DB{
 
    public $connection;
 
    public function __construct()
    {
        $this->connect();
    }
   
    public function Connect()
    {
        try{
            //connect to db
            $this->connection = mysql_connect(SERVER,DB_USER,DB_PWD); //these are functions, not classes like mysqli get rid of new
           
            //concatenate something like this on the end of the string?
            mysql_select_db(DB_NAME);
 
            //check for connection error
            if(mysql_error())
                throw new Exception(mysql_error());
            else
            return $this->connection;
 
        }catch(Exception $e){
            echo("Connection failed, try again later" . $e->getMessage());
        }
    }
}
 
wibblywobbly
Forum Newbie
Posts: 17
Joined: Mon Oct 19, 2009 10:11 am

Re: local server vs server server

Post by wibblywobbly »

Hmm I'm not getting this,

I'm back to my original error and I no longer have the script working on my local server. Forgive me for posting ALL my code, but I suspect this is something fairly simple.

The error on my server is:

Code: Select all

Fatal error: Call to a member function query() on a non-object in /home/username/public_html/classes/Authenticate.php on line 27
Here's the index.php page with the username and password box

Code: Select all

<?php
 
//require file contains links to the classes and the config file.
require_once("inc.php");
 
//check for a click on submit button
if (isset($_POST['submit']) || isset($_POST['submit_x'])) 
{
    //both fields are required
    if("" != $_POST['username'] && "" != $_POST['password']){
 
        //create instance of authenticate class
        $userLogin = new Authenticate($_POST['username'], $_POST['password']);
        $userLogin->UserLogin();
        if($userLogin->Success()){
 
            //set the session values
            $_SESSION['validUser'] = $userLogin->data[0]['username'];
            $_SESSION['address'] = $userLogin->data[0]['address'];
            $_SESSION['name'] = $userLogin->data[0]['name'];
 
            //redirect user to their page, the address is taken from the database
            $address = $userLogin->data[0]['address'];
            header("location: " . "$address");
            exit();
 
            }else{
                $message = "Incorrect Username or Password";
            }
 
    } else{
        $message = "Both fields are required";
    }
}
//?>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page</title>
    <link href="stylesheet.css" rel="stylesheet" type="text/css">
    </head>    
  
    
<body>
    
    <div class="container" id="container">
    <div class = "contact_form" id = "contact_form">
        <form name="contact" method="post" action="<?php echo($_SERVER['PHP_SELF']);?>">
 
        <label for="username" id="username_label"><img src="images/username.png" width="82" height="14" alt="username" /></label>
        <input type="text" name="username" id="username" class="text-input" />
              
        <label for="passwrod" id="password_label"><img src="images/password.png" width="84" height="20" alt="password" /></label>
        <input type="password" name="password" id="passwrod" value="" class="text-input" />
              
        <br />
        <input type="image" name="submit" class="button" id="submit_btn" src="images/transparent.gif"/>
        </form>
       
       <div class="error" id="error"><?php if($message) echo($message); ?></div>
</div>
       
</body>
</html>
Here's the new amended Db.php class (many thanks for your help updating this!):

Code: Select all

<?php
 
//this class will establish a db connection WITHOUT using the mysqli driver
 
class DB{
 
    public $connection;
 
    public function __construct()
    {
        $this->connect();
    }
 
    public function Connect()
    {
        try{
            //connect to db
            $this->connection = mysql_connect(SERVER,DB_USER,DB_PWD); //these are functions, not classes like mysqli get rid of new
 
            //is this actually selecting the database, I'm not convinced it works...
            mysql_select_db(DB_NAME);
 
            //check for connection error
            if(mysql_error())
                throw new Exception(mysql_error());
            else
            return $this->connection;
 
        }catch(Exception $e){
            echo("Connection failed, try again later" . $e->getMessage());
        }
    }
}
 
?>
Now the Authenticate.php class:

Code: Select all

<?php
 
class Authenticate{
 
    private $db;
    public $data;
    private $success = false;
 
    private $username;
    private $password;
 
    public function __construct($username, $password)
    {
        $this->db = new DB();
        $this->username = $username;
        $this->password = $password;
    }
 
    private function Checking()
    {
        
        try{
         //set sql query
         $sql = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
 
         //execute query and store the result
         $result = $this->db->connection->query($sql);
 
         //test
         if(!$result)
            throw new Exception($sql . $this->db->connection->error);
         else{
             return $result;
         }
 
        }catch(Exception $e){
            echo("Login query failed: " . $e->getMessage());
        }
 
    }
 
    //break the result into an array so the address can be carried
    public function UserLogin()
    {
        //call the fetch function to get the query results
        $userdetails = $this->Checking();
 
        //loop through the set and create and array
        while($row = $userdetails->fetch_assoc()){
            $this->data[] = array('id'=>$row['id'],
                            'username' => $row['username'],
                            'password' => $row['password'],
                            'address' => $row['address'],
                            'name' => $row['name'],
                            );
        }
        if(!$this->data){}
        else{
            $this->data;
            return $this->success = true;
        }
    }
 
    public function Logout()
    {
        unset($_SESSION['validUser']);
        session_destroy();
    }
 
    // return the current value of success property
    public function Success()
    {
        return $this->success;
    }
 
}
 
?>
The config.php simply sets the database settings:

Code: Select all

<?php
// project configuration
 
define("SERVER","localhost");
define ("DB_USER","root");
define("DB_PWD","root");
define("DB_NAME","users");
 
session_start();
 
?>
And the inc.php file:

Code: Select all

<?php
 
//load config parameters
require_once("config.php");
 
//application classes
require_once("classes/Authenticate.php");
require_once("classes/DB.php");
 
?>
 
The table is called "users" and contains id, username, password, address, name

THAT'S IT!

Does this post do anything for anyone? It would be great if you could help me out, as I mention, I'm fairly sure this is something simple. Any advance would be greatly appreciated!

-- wibblywobbly
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

Re: local server vs server server

Post by Griven »

I've modified your code a bit to eliminate redundancies. Please note that I have not tested this code.

DB.php

Code: Select all

class DB{
 
    function __construct() {
        //connect to db
        $connect = mysql_connect(SERVER,DB_USER,DB_PWD);
        if (!$connect){
            echo 'Error establishing database connection';
            exit();
        }
        
        $selectdb = mysql_select_db(DB_NAME);
        if (!$selectdb){
            echo 'Error selecting database';
            exit();
        }
    }
    
    public function query($string){
        $result = mysql_query($string);
        if (!$result){
            echo 'Error returning dataset';
        } else {
            return $result;
        }
    }
    
}
Here, I've moved your connection details to the __construct function to simplify things. In addition, I've removed the "private" declaration from the __construct function, as it is private anyway. In addition, I've added the "query()" function that you were trying to use. In your code, it didn't exist, and so it was throwing errors.

You may now run a query by using the following code:

Code: Select all

$db = new DB;
$stuff = $db->query("SELECT * FROM db");
NOTE: Create a $db object in a location that is common to all the files that will need a database connection, such as your configuration file.

Now, on to your authentication page. Try this:

Code: Select all

class Authenticate{
      //global $db will allow your class to access the $db object that you created in your code's common area according to my note above.
    global $db;
    public $data;
    private $success = false;
 
    private $username;
    private $password;
 
    public function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
 
    private function Checking()
    {
       
        try{
         //set sql query
         $sql = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
 
         //execute query and store the result
         $result = $db->query($sql);
 
         //test
         if(!$result)
            throw new Exception($sql . $db->error);
         else{
             return $result;
         }
 
        }catch(Exception $e){
            echo("Login query failed: " . $e->getMessage());
        }
 
    }
 
    //break the result into an array so the address can be carried
    public function UserLogin()
    {
        //call the fetch function to get the query results
        $userdetails = $this->Checking();
 
        //loop through the set and create and array
        while($row = $userdetails->fetch_assoc()){
            $this->data[] = array('id'=>$row['id'],
                            'username' => $row['username'],
                            'password' => $row['password'],
                            'address' => $row['address'],
                            'name' => $row['name'],
                            );
        }
        if(!$this->data){}
        else{
            $this->data;
            return $this->success = true;
        }
    }
 
    public function Logout()
    {
        unset($_SESSION['validUser']);
        session_destroy();
    }
 
    // return the current value of success property
    public function Success()
    {
        return $this->success;
    }
 
}
Post Reply