Reading data from database table

Spread the love

 

PHP is having multiple functions for reading data from database table. Those functions are mysql_fecth_array, mysql_fetch_assoc, mysql_fetch_object. We will see mysql_fetch_array in this chapter.

While reading data from a table, these functions fetch data in the form of a single row at a time. Then we have to loop through to fetch all the rows of the table. mysql_fetch_array() function returns fetches row’s data in the form of an associative array or numeric array or both. If no data found then this function will return you False.

Create a new file named employee_data.php and add below code.

<?php

require_once("dbconnection.php");

$query = "select * from employees";
$result = mysql_query($query, $con);

if(!$result)
{
die('Error getting table data', mysql_error);
}

while($row = mysql_fetch_array($result))
{
echo "Employee Name - ".$row['name'];
echo "<br>Employee Username - ".$row['username'];
}
?>

In above example, you will get data in both associative and numeric array format. If you want to get data only in the numeric array you have to pass a second parameter “MYSQL_NUM” in mysql_fetch_array like $row = mysql_fetch_array($result,MYSQL_NUM). And from the associative array, the second parameter will be “MYSQL_ASSOC”.

To get only associative array directly you can use the mysql_fetch_assoc function. This will fetch data in the form of an associative array.


Spread the love

Leave a Comment