PHP -Mysql query help required

by 5 replies
6
I have many records in the table I want to fetch only first 5 records from the table using query of mysql and print into php. Can anyone tell me how can i do it?
#programming #mysql #php #query #required
  • SELECT * FROM yourtable LIMIT 0,5

    http://dev.mysql.com/doc/refman/5.0/en/select.html
  • This is the complete php code which you can run. Create a blank php file and paste this code:

    <?php
    $dbhost = 'YOUR DB HOST HERE'; /* mostly "localhost" */
    $dbname = 'YOUR DB NAME HERE';
    $dbuser = 'YOUR DB USERNAME HERE';
    $dbpass = 'YOUR DB PASSWORD HERE';

    $con = mysql_connect($dbhost, $dbname, $dbpass) or die("Database connection error.");

    if($con){
    mysql_select_db($dbname) or die("Invalid Database");
    }

    $tablename = "YOUR TABLENAME HERE";
    $data = array();

    $query = "SELECT * FROM $tablename LIMIT 0,5";
    $result = mysql_query($query) or die("Invalid SQL Query");

    if(mysql_num_rows($result)){
    while($row = mysql_fetch_assoc($result)){
    array_push($data, $row);
    }
    }

    echo '<pre>';
    print_r($data); /* Here your data in $data array */
    echo '</pre>';
    • [1] reply
    • Great tutorial but use mysqli instead of old mysql
  • You can just use sql query for it select * from tablename limit 0,5 where 0 is start index and 5 is number of records then you can print in php using mysql_fetch_array , make an array and in the loop you can print each field using echo
  • Using LIMIT option we can filter the top first 5 records. Limit is used to limit your MySQL query results to those that fall within a specified range. You can use it to show the first X number of results, or to show a range from X - Y results. It is phrased as Limit X, Y and included at the end of your query. X is the starting point (remember the first record is 0) and Y is the duration (how many records to display). Also Known As: Range Results Examples:
    SELECT * FROM `your_table` LIMIT 0, 5

Next Topics on Trending Feed