Solved

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

Posted on 2010-09-10
6
1,290 Views
Last Modified: 2012-05-10
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
Comment
Question by:Steggs
  • 3
  • 2
6 Comments
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 350 total points
ID: 33652272
You are using a object oriented syntax but $con is a variable not an object. Write this

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

Best
0
 
LVL 30

Accepted Solution

by:
Marco Gasi earned 350 total points
ID: 33652284
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
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 33652736
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 30

Author Comment

by:Steggs
ID: 33653248
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
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 33653275
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
 
LVL 30

Author Closing Comment

by:Steggs
ID: 33654002
thanks guys
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now