0

hi, i am new to mysql and also to php, i am trying to add a feature to a webpage, for showing some latest records from a mysql databse. i managed to show records from mysql database, but the problem is i only trying to show the first four records but it shows all the records i have in my databse. here is my script that shows the data from the database, so how do i managed to do that!!

<?php
$db = mysql_connect($mysql_server, $mysql_username, $mysql_password);
if (!$db)
{
   die('Failed to connect to database server!<br>'.mysql_error());
}
mysql_select_db($mysql_database, $db) or die('Failed to select database<br>'.mysql_error());
$sql = "SELECT id, name, seo_friendly_url FROM " . $mysql_table . "PAGES WHERE visible = 1 ORDER BY menu_index ASC";
$result = mysql_query($sql, $db);
while ($data = mysql_fetch_array($result))
{
   echo "<a href=\"" . basename(__FILE__) . "?page=" . $data['seo_friendly_url'] . "\" id=\"" . $data['id'] . "\">" . $data['name'] . "</a>\n";
}
mysql_close($db);
?>

thanx.

3
Contributors
6
Replies
25
Views
4 Years
Discussion Span
Last Post by Eagle.Avik
0
$sql = "SELECT id, name, seo_friendly_url FROM {$mysql_table}PAGES WHERE visible = 1 ORDER BY menu_index LIMIT 4";
$r = mysql_query($sql);
if(mysql_num_rows($r))
{
    while($d = mysql_fetch_assoc($r))
    {
        echo $d['field'];
        //do what you want
    }
}

I suggest using mysqli_* or PDO though as mysql_* is to be deprecated.

0

Hey.

You can add a LIMIT clause to your SQL query to specify how many you want.

SELECT stuff FROM the_table 
ORDER BY id DESC 
LIMIT 4

Assuming id is an AUTO_INCREMENT field, this query would give you only the latest four records. The ORDER BY is returning the results in descendinc order (DESC), and the LIMIT is only giving you the first four of those records.

Edited by Atli

0

Ah, missed the latest records :)

$sql = "SELECT id, name, seo_friendly_url FROM {$mysql_table}PAGES WHERE visible = 1 ORDER BY menu_index DESC LIMIT 4";
0

What do you mean full edited code?

I showed you the SQL. I demonstrated the conditional (if) and the while loop. I don't know what else you want me to do? Are you not able to insert your own code into the loop?

0

@diafol, sorry for asking that previously. got it working now... thanx soooo much.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.