trying to get values from database

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Post Reply
beginner123
New php-forum User
New php-forum User
Posts: 33
Joined: Fri Jan 20, 2012 10:39 am

trying to get values from database

Post by beginner123 » Thu Oct 04, 2012 9:48 am

I am creating a webiste that sells musical instruments. I have a database created and now I want the website to access the database but I'm getting this error: Notice: Trying to get property of non-object in C:\wamp\www\querydb.php on line 21
(line 21 is

Code: Select all

$num_results = $result->num_rows; 
)
here is my code:

Code: Select all

<html> 
<head> 
<title>Products</title> 
</head> 

<h2> These are a list of the products we currently have for sale</h2> 

<?php 

@$db = new mysqli( 'localhost', 'root', '', 'products'); 

if (mysqli_connect_errno()) { 
echo 'error connecting to db'; 
exit; 
} 

$query = "SELECT * from products"; 

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

$num_results = $result->num_rows; 

echo 'Number of products found : <strong>' . $num_results . '</strong><br><br>'; 

?> 

<table width="1200" border="2">

<tr> 
<th>Product Number</th> 
<th>Product Description</th> 
<th>Quantity On Hand</th> 
<th>Price</th> 
<th>Image</th> 
</tr> 

<?php 
for ($i=0; $i < $num_results; $i++) { 

$row = $result->fetch_object(); 

$product_number = $row->product_number; 
$product_description = $row->product_description; 
$quantity_on_hand = $row->quantity_on_hand; 
$price = $row->price; 
$image = $row->image; 
//$formattedPrice = number_format($price, 2, '.', ','); 

echo '<tr>'; 
echo "<td>$product_number</td>"; 
echo "<td>$product_description</td>"; 
echo "<td>$quantity_on_hand </td>";
echo "<td>$price</td>"; 
echo "<td>$image</td>"; 
//echo "<td>€$formattedPrice</td>"; 
//echo "<td><img src='images/title_new'/></td>"; 
echo '<tr>'; 

} 

echo '</table>'; 

//$result->free(); 
$db->close(); 
?> 

<body> 
</body> 
</html>

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Re: trying to get values from database

Post by seandisanti » Thu Oct 04, 2012 12:49 pm

$result isn't an object, it doesn't have a num_rows property. Your code defines $result as

Code: Select all

$result = $db->query($query); 
perhaps try it like this....

Code: Select all

$result = $db->query($query);
$result_set = mysqli_fetch_array($result);
$num_results = mysqli_num_rows($result_set);

beginner123
New php-forum User
New php-forum User
Posts: 33
Joined: Fri Jan 20, 2012 10:39 am

Re: trying to get values from database

Post by beginner123 » Fri Oct 05, 2012 10:09 am

I now get these errors:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\querydb.php on line 20

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\querydb.php on line 21

Post Reply

Who is online

Users browsing this forum: Baidu [Spider], Bing [Bot] and 5 guests