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.

Recommended Answers

All 6 Replies

Member Avatar for diafol
$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.

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.

Member Avatar for diafol

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";

@diafol thnx, but can you give me the full edited code

Member Avatar for diafol

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?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.