Writing Functions with mysql_fetch_object()
Below is an example of how to use mysql_fetch_object().
<?php function getUser($userid){ $result = mysql_query("select * from user where userid=".$userid); // this will return false if there are no rows found // since there is only 1 result possible with a userid // i do not need this in a while loop. return mysql_fetch_object($result); } ?>
Now let's look at an example when we would get multiple users in our result. The best way to do this is create an array of objects.
<?php function getUsers(){ // create an array so we know we're always returning an array $array = array(); // run the query $result = mysql_query("select * from user"); // loop through the dataset and append the array with objects while($object = mysql_fetch_object($result)){ $array[]=$object; } return $array; } // here is how we would use this $user_array = getUsers(); foreach($user_array as $user_object){ echo $user_object->firstname . " " . $user_object->lastname . "<br>\n"; } ?>
Thanks for reading.
One tip that you would want
One tip that you would want to bear in mind when designing large scale systems is that you don't want to query SQL using "SELECT *" if the only fields you're interested in are firstname and lastname. Rather use "SELECT firstname, lastname FROM user", as it uses less memory.
Just the bit of code I
Just the bit of code I needed.. what a champ!
Post new comment