My Stuff
Username

Password

Articles/Snippets
ASP Classic
C
C#
C++
CSS
HTML
Java
Javascript
MySQL
Perl
PHP
Python
Ruby
Unix/Linux/BSD
VB 6
VB.NET


Writing Functions with mysql_fetch_object()


Your rating: None Average: 4 (1 vote)

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

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: [code], [blockcode], [asp], [awk], [c], [cpp], [csharp], [drupal5], [drupal6], [java], [javascript], [jquery], [mysql], [perl], [perl6], [php], [python], [ruby], [sql], [vb], [vbnet], [xml].
  • Use to create page breaks.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.