[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1348
  • Last Modified:

Fatal error: Call to a member function query() on a non-object in

Hey guys,

I'm trying to learn php and making my first cart at the moment. Found a tutorial online and have been able to save the cart contents into a session but I'm stuck on how to connect to the database to match the cart with the products in the database table.

this line

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

is causing the error...

Any help appreciated

<?php
		
		// login details for database
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';

// connect to database
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die                      ('Error connecting to mysql');

// select products database
//mysql_select_db("futurek0_products", $con);

		$total = 0;
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE ID = '.$id;
$result = $con->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>&pound;'.($PRODUCT_PRICE * $qty).'</td>';
$total += $PRODUCT_PRICE * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: &pound;'.$total.'</p>';

?>

Open in new window

0
Mark Steggles
Asked:
Mark Steggles
  • 3
  • 2
3 Solutions
 
Marco GasiFreelancerCommented:
You are using a object oriented syntax but $con is a variable not an object. Write this

$result = mysql_query($sql,$con);

Best
0
 
Marco GasiFreelancerCommented:
To use that syntax you have first to create an object. You can do this if the tutorial you found is object oriented (maybe you can past a link to that tutorial so I can see it). But if in the rest of your script you never used oop syntax (such as $con->$query, that is $object->$attribute or $method), then it's more probable you have not tu use that syntax at all and write as I said. In this case you have to change other statements also: $row = $result->fetch() becomes $row = mysql_fetch_array($result);)

Let me know
0
 
Ray PaseurCommented:
Here is an example showing how to do some of the basics in MySQL.  Take careful note of the error handling.  MySQL is not a black box; it can and will fail for reasons that are outside of your control.  Hopefully you can adapt these principles to your code.

You might also enjoy this book.   Great examples and a downloadable code library that you can copy and use in your own scripts.  It has been part of my professional library since Version One.
http://www.sitepoint.com/books/phpmysql4/

Best, ~Ray
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// IMPORTANT PAGES FROM THE MANUALS
// MAN PAGE: http://us2.php.net/manual/en/ref.mysql.php
// MAN PAGE: http://us2.php.net/manual/en/mysql.installation.php
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB CONNECTION: ";
   echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB SELECTION: ";
   echo "<br/> $errmsg <br/>";
   die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES




// ESCAPING A DATA FIELD FOR USE IN MYSQL QUERIES
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-real-escape-string.php
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATING AND SENDING A SELECT QUERY AND TESTING THE RESULTS
// MAN PAGE:http://us2.php.net/manual/en/function.mysql-query.php
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-num-rows.php
$num = mysql_num_rows($res);
if (!$num)
{
   echo "<br/>QUERY FOUND NO DATA: ";
   echo "<br/>$sql <br/>";
}
else
{
   echo "<br/>QUERY FOUND $num ROWS OF DATA ";
   echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-fetch-assoc.php
echo "<pre>\n"; // MAKE IT EASY TO READ
while ($row = mysql_fetch_assoc($res))
{
   // MAN PAGE: http://us2.php.net/manual/en/function.var-dump.php
   var_dump($row);
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
// MAN PAGE: http://us.php.net/mysql_fetch_array
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES (\"$safe_username\")";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-insert-id.php
$id  = mysql_insert_id($db_connection);

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Mark StegglesWeb DeveloperAuthor Commented:
Thanks marqusG,

I reworked the code (see attached) from your advice and am now getting results. The tutorial I was using is http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart

--

Thanks Ray, that code looks helpful.

--

One problem is that I'm only getting one result back when I loop through the cart. Something wrong with

foreach ($contents as $id=>$qty) {  ?



Thanks
<?php
		
$total = 0;
echo '<table id="cart" cellspacing="0" cellpadding="0">
			<tr>
				<th>Product</th><th>Quantity</th><th>Price</th><th>Total</th><th>Remove</th>
			</tr>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE ID = '.$id;
$result = mysql_query($sql,$con);
$row = mysql_fetch_array($result);
extract($row);
echo '<tr>';
echo '<td>' . $row['PRODUCT_DESC'] . '</td>';
echo '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
echo '<td>$' . $row['PRICE'] . '</td>';
echo '<td>$' . ($row["PRICE"] * $qty) . '</td>';
echo '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
$total += $row['PRICE'] * $qty;
echo '</tr>';
}
echo '</table>';
echo '<p>Grand total: $'.$total.'</p>';

?>

Open in new window

0
 
Marco GasiFreelancerCommented:
Try write

$sql = 'SELECT * FROM products WHERE ID = '.$id; //why dot? it misses a '

$sql = 'SELECT * FROM products WHERE ID = '$id';

Then use this

while ($row = mysql_fetch_array($result){
  echo '<tr>';
  echo '<td>' . $row['PRODUCT_DESC'] . '</td>';
  echo '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
  echo '<td>$' . $row['PRICE'] . '</td>';
  echo '<td>$' . ($row["PRICE"] * $qty) . '</td>';
  echo '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
  $total += $row['PRICE'] * $qty;
  echo '</tr>';
}

I stronglky recommend you to read this tutorial and related book: http://articles.sitepoint.com/article/php-mysql-tutorial.

Good luck
0
 
Mark StegglesWeb DeveloperAuthor Commented:
thanks guys
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now