PDA

Click to See Complete Forum and Search --> : [RESOLVED]Write function to get all records?


rasana
Nov 6th, 2008, 04:36 AM
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


$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;
}

the182guy
Nov 6th, 2008, 05:05 AM
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.


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:

$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.

rasana
Nov 6th, 2008, 05:31 AM
Thank you the182guy!!!! :)
its working.. :thumb: