MySQL Fetch Object Using PHP
Show records using mysql_fetch_object( ) function
mysql_fetch_object() return the rows from the number of records available in the database as an object. at a time it return only the first row as an object. if we want to retrieve all the records of the table then we must put this function inside the while loop.
Syntax:
mysql_fetch_object(query)
PHP MySQL Select Query Using mysql_fetch_object() With Output Example
<?php
$host = "localhost";
$user = "";
$pass = "";
$dbname = "users";
$conn = mysql_connect($host,$user,$pass) or die(mysql_error());
if(!$conn){
die("Could not connect:".mysql_connect_error());
}
// select database
mysql_select_db($dbname,$conn);
$sql = "SELECT * FROM users";
$result=mysql_query($sql);
$results=mysql_fetch_object($result);
echo $results->name;
mysql_close();
?>
Output:
Rakesh
Show all records from users table using mysql_fetch_object( ) function:
<?php
$host = "localhost";
$user = "";
$pass = "";
$dbname = "users";
$conn = mysql_connect($host,$user,$pass) or die(mysql_error());
if(!$conn){
die("Could not connect:".mysql_connect_error());
}
// select database
mysql_select_db($dbname,$conn);
$sql = "SELECT * FROM users";
$retval=mysql_query($sql);
if(mysql_num_rows($retval) > 0){
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Salary</th></tr>";
while($row= mysql_fetch_row($retval))
{
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->name."</td>";
echo "<td>".$row->salary."</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "0 results";
}
mysql_close();
?>
Output:
Result In Table: Users
| id | name | salary |
|---|---|---|
| 1 | Name1 | 55000 |
| 2 | Name2 | 70000 |
Series:
MySql Tutorials Hub
