[RESOLVED]Write function to get all records?
Hi All,
I'm working on a project where I have to write a function to get all records from a table which will return array of objects.
I've written a function to get a single record from table and working fine..but to get all records i'll have to write while loop..how would I store data in array and how would I display all data...?
Below is function to get a single record
PHP Code:
$sql = "select * from student where id = 1";
$getData = $db->getRecord($sql);
function getRecord($sql)
{
$result = mysql_query($sql) or die(mysql_error());
$data_set = mysql_fetch_array($result);
return $data_set;
}
Re: Write function to get all records?
Hi rasana,
Here's a function similar to yours, that will return whats known as a 'jagged' array - basically an array where each element is another array. So in this case, each element of the first array is a set of data about a single student.
PHP Code:
function getRecords($sql)
{
$output = array();
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
//loop through each row returned, and store it in an array to return
$output[] = $row;
}
return $output;
}
Here's one way to loop through the data and display it:
PHP Code:
$students = getRecords("SELECT * FROM students");
foreach($students as $student)
{
//here you now have access to all the fields from the table
echo $student['name'];
}
You could add some code to check that some rows were returned from the query, and possibly return false if none found, then when processing the array you can check if the result was false or is_array().
If you don't fully understand how the result array of the function works, do a print_r($students) and it will show you.
Re: Write function to get all records?
Thank you the182guy!!!! :)
its working.. :thumb: