Jump to content

Query 5 latest users with PHP and PEAR


notepad

Recommended Posts

Hey, I am trying to get the latest 5 users out of my database. I made this snippet of PHP but I can't seem to get it to echo right. Does anyone see what I am missing here?

 

btw, I have it ordered by 'id' because I setup an auto_increment id row. And '$db' is the database connection from the db_connect.php file.

 

<?php

require('db_connect.php');

$latest = $db->query("SELECT * FROM users");
$latest->orderBy('id DESC');
$latest->limit(5);
$latest->find();
while ($latest->fetch('username')) {
    echo "<a href=\"profiles.php?id=$latest->username\">$latest->username</a><BR>";
}

if(DB::isError($latest)) {
    die($latest->getMessage());
}

?>

 

~ Brandon

Link to comment
https://forums.phpfreaks.com/topic/47510-query-5-latest-users-with-php-and-pear/
Share on other sites

I have no idea how your database class works so I can't really help you using it... but normally you would do it like this...

 

(I assume you already have an active database connection in $connection so I wont post that part of the script)

 

<?php
$result = mysqli_query($connection, 'SELECT * FROM users ORDER BY id DESC LIMIT 5') or die(mysqli_error($connection));
while($row = mysqli_fetch_assoc($result))
{
   echo '<a href="profiles.php?id=' . $row['username'] . '">' . $row['username'] . '</a><br>';
}
?>

Hey,

 

My database class, uses the PEAR classes(pear.php.net).  It is pretty much just library of database functions, and fits in nicely with PHP.  I am still pretty new to it (hence my problems), but I am trying to learn it.  But I did get it working, using this code:

 

<?php

require('db_connect.php');

$latest =& $db_object->query("SELECT * FROM users ORDER BY id DESC LIMIT 5");
while ($latest->fetchInto($row)) {
   echo '<a href="profiles.php?id=' . $row['username'] . '">' . $row['username'] . '</a><br>';
}

if(DB::isError($latest)) {
    die($latest->getMessage());
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.