Layla
Layla

Reputation: 143

mysql_fetch_object() warning

I'm trying to output a table from my database by using PHP, but shows "mysql_fetch_object(): supplied argument is not a valid MySQL result resource".

// Connect to MySQL server
$conn = mysql_connect('localhost','root','') or die(mysql_error());

// Select database
mysql_select_db('bakery') or die(mysql_error()); 

$sql = "Select * From customer";
$result = mysql_query($sql,$conn);

echo "<table border=1>"; 
echo "<tr><td>custid</td>
<td>custname</td>
<td>ccn</td>
<td>phoneno</td>
<td>address</td>
<td>city</td>
<td>zip</td></tr>"; 
while($row = mysql_fetch_object($sql))
echo "<tr><td>$row->custid</td>
<td>$row->custname</td>
<td>$row->ccn</td>
<td>$row->phoneno</td>
<td>$row->address</td>
<td>$row->city</td>
<td>$row->zip</td></tr>"; 
echo "</table>"; 

Upvotes: 1

Views: 477

Answers (1)

Instead of

while($row = mysql_fetch_object($sql))

It should be

while($row = mysql_fetch_object($result))  //<--- Pass the $result

As the error states... The mysql_fetch_object expects a resource , but you had passed a string (That was main error behind this)


This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

Upvotes: 1

Related Questions