Jump to content

[SOLVED] call to function on a non object


aebstract

Recommended Posts

I'm getting two errors, but the second one is what has me worried as I have never had this sort of error and don't know what could be causing it. I'm using a bunch of code to get me started on a cart, which is:

 


<?php



/**
* MySQL Database Connection Class
* @access public
* @package SPLIB
*/
class MySQL {
    /**
    * MySQL server hostname
    * @access private
    * @var string
    */
    var $host;

    /**
    * MySQL username
    * @access private
    * @var string
    */
    var $dbUser;

    /**
    * MySQL user's password
    * @access private
    * @var string
    */
    var $dbPass;

    /**
    * Name of database to use
    * @access private
    * @var string
    */
    var $dbName;

    /**
    * MySQL Resource link identifier stored here
    * @access private
    * @var string
    */
    var $dbConn;

    /**
    * Stores error messages for connection errors
    * @access private
    * @var string
    */
    var $connectError;

    /**
    * MySQL constructor
    * @param string host (MySQL server hostname)
    * @param string dbUser (MySQL User Name)
    * @param string dbPass (MySQL User Password)
    * @param string dbName (Database to select)
    * @access public
    */
    function MySQL ($host,$dbUser,$dbPass,$dbName) {
        $this->host=$host;
        $this->dbUser=$dbUser;
        $this->dbPass=$dbPass;
        $this->dbName=$dbName;
        $this->connectToDb();
    }

    /**
    * Establishes connection to MySQL and selects a database
    * @return void
    * @access private
    */
    function connectToDb () {
        // Make connection to MySQL server
        if (!$this->dbConn = @mysql_connect($this->host,
                                      $this->dbUser,
                                      $this->dbPass)) {
            trigger_error('Could not connect to server');
            $this->connectError=true;
        // Select database
        } else if ( !@mysql_select_db($this->dbName,$this->dbConn) ) {
            trigger_error('Could not select database');
            $this->connectError=true;
        }
    }

    /**
    * Checks for MySQL errors
    * @return boolean
    * @access public
    */
    function isError () {
        if ( $this->connectError )
            return true;
        $error=mysql_error ($this->dbConn);
        if ( empty ($error) )
            return false;
        else
            return true;
    }

    /**
    * Returns an instance of MySQLResult to fetch rows with
    * @param $sql string the database query to run
    * @return MySQLResult
    * @access public
    */
    function query($sql) {
        if (!$queryResource=mysql_query($sql,$this->dbConn))
            trigger_error ('Query failed: '.mysql_error($this->dbConn).
                           ' SQL: '.$sql);
        return new MySQLResult($this,$queryResource);
    }
}

/**
* MySQLResult Data Fetching Class
* @access public
* @package SPLIB
*/
class MySQLResult {
    /**
    * Instance of MySQL providing database connection
    * @access private
    * @var MySQL
    */
    var $mysql;

    /**
    * Query resource
    * @access private
    * @var resource
    */
    var $query;

    /**
    * MySQLResult constructor
    * @param object mysql   (instance of MySQL class)
    * @param resource query (MySQL query resource)
    * @access public
    */
    function MySQLResult(& $mysql,$query) {
        $this->mysql=& $mysql;
        $this->query=$query;
    }

    /**
    * Fetches a row from the result
    * @return array
    * @access public
    */
    function fetch () {
        if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) {
            return $row;
        } else if ( $this->size() > 0 ) {
            mysql_data_seek($this->query,0);
            return false;
        } else {
            return false;
        }
    }

    /**
    * Returns the number of rows selected
    * @return int
    * @access public
    */
    function size () {
        return mysql_num_rows($this->query);
    }

    /**
    * Returns the ID of the last row inserted
    * @return int
    * @access public
    */
    function insertID () {
        return mysql_insert_id($this->mysql->dbConn);
    }

    /**
    * Checks for MySQL errors
    * @return boolean
    * @access public
    */
    function isError () {
        return $this->mysql->isError();
    }
}


function checkNum($checknum){
  return ($checknum%2) ? TRUE : FALSE;
}


$host = 'localhost';
$user = 'berryequipment';
$pass = 'gU8Kso8Y';
$name = 'berryequipment_net_db';
$db = &new MySQL($host,$user,$pass,$name);


function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '(0)';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '(<a href="cart.php">'.count($items).'</a>)';
}
}



function showCart() {
$cart = $_SESSION['cart'];
if ($cart) {
	$items = explode(',',$cart);
	$contents = array();
	foreach ($items as $item) {
		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
	}
	$output[] = '<form action="index.php?page=cart&action=update" method="post" id="cart">';
	$output[] = '<table>';
	foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM p_products WHERE id = '.$id;
		$result = $db->query($sql);
		$row = $result->fetch();
		extract($row);
		$output[] = '<tr>';
		$output[] = '<td><a href="index.php?page=cart&action=delete&id='.$id.'" class="r">Remove</a></td>';
		$output[] = '<td>'.$title.' by '.$author.'</td>';
		$output[] = '<td>£'.$price.'</td>';
		$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
		$output[] = '<td>£'.($price * $qty).'</td>';
		$total += $price * $qty;
		$output[] = '</tr>';
	}
	$output[] = '</table>';
	$output[] = '<p>Grand total: £'.$total.'</p>';
	$output[] = '<div><button type="submit">Update cart</button></div>';
	$output[] = '</form>';
} else {
	$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}



?>

 

My errors are:

 

Notice: Undefined variable: db in /home/virtual/site21/fst/var/www/html/performance/functions.php on line 232

 

Fatal error: Call to a member function query() on a non-object in /home/virtual/site21/fst/var/www/html/performance/functions.php on line 232

Link to comment
Share on other sites

This is the line causing the error.

 

 

$result = $db->query($sql);

 

$db is not defined is causing the second error Call to a member function query()

 

That means for some $db = &new MySQL($host,$user,$pass,$name); is not being processed before $result = $db->query($sql);

 

just make sure your call to showCart() happens after including this function file and I believe it will be ok.

 

Something like this.

 

require_once('performance/functions.php');
showCart();

 

Link to comment
Share on other sites

Here's the problem with that. I have it included at the very top of my index.php file, before anything else happens. Not only that, I removed it from there and tryed it just like you showed on my cart.php and I am still getting the error. Is something out of order in the actual functions.php?

Link to comment
Share on other sites

Wherever you call show showCart();, change it to...

 

// method #1

 

showCart ( $db );

 

 

or declare global in the function...

 

 

// method #2

 

function showCart() {

   global $db;
   $cart = $_SESSION['cart'];
   if ($cart) {

//...

 

then call it as before (for method #2)

 

showCart ();

 

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.