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.

Re: get only first few records from mysql database and show them through php 80 80
Member Avatar
$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.

Re: get only first few records from mysql database and show them through php 80 80

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.

Re: get only first few records from mysql database and show them through php 80 80
Member Avatar

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";
Re: get only first few records from mysql database and show them through php 80 80

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

Re: get only first few records from mysql database and show them through php 80 80
Member Avatar

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?

Re: get only first few records from mysql database and show them through php 80 80

@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 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.