php and mysql selecting 5 rows from mysql
i am tryng to select 5 mysql rows from the database and display them like $row[1] ect.... in php i am not sure how to do it an someone lead me down the right way please开发者_开发技巧 Ok i hav looked a bit more
i wanted it to come out 1 - 5 and i wanted it to display the names
$result = mysql_query("SELECT * FROM table ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$arr = array("somearray" => array(1 => 5, 2 => 9, 3 => 42, 4 => 42, 5 => 42));
echo $arr["somearray"][1];
echo $arr["somearray"][2];
echo $arr["somearray"][3];
echo $arr["somearray"][4];
echo $arr["somearray"][5];
}
I think the OP wants five ROWS, not COLUMNS. Here is the correct code, assuming you already have a mysql connection open:
$sql = 'SELECT *
FROM table_name
ORDER BY col_name
LIMIT 5';
$result = mysql_query($sql);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row[] = $line;
}
// print (access individual rows: $row[0] ... $row[4])
var_dump($row);
From php.net : http://us3.php.net/manual/en/function.mysql-fetch-row.php
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Try using MySQL's LIMIT
clause to limit your results to 5 rows. And use PHP's mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_row() (returns a numerically indexed array). Also, it's good practice to free the memory associated with the result using mysql_free_result().
$result = mysql_query("SELECT * FROM mytable ORDER BY id DESC LIMIT 5") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
echo $name;
}
mysql_free_result($result);
If you only need to select 5 rows from MySQL you can do this:
SELECT *
FROM Table
ORDER BY column
LIMIT 5
精彩评论