|
-
Nov 6th, 2008, 05:36 AM
#1
Thread Starter
Lively Member
[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;
}
Last edited by rasana; Nov 6th, 2008 at 06:32 AM.
-
Nov 6th, 2008, 06:05 AM
#2
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.
Last edited by the182guy; Nov 6th, 2008 at 06:08 AM.
Chris
-
Nov 6th, 2008, 06:31 AM
#3
Thread Starter
Lively Member
Re: Write function to get all records?
Thank you the182guy!!!!
its working..
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|