2009-10-23 56 views
0

我尝试从数据库中选择5个mysql行并将它们显示为$ row [1] ect ....在php中我不确定如何做到这一点有人引导我降权的方式请 好吧,我甲肝看上去有点更php和mysql从mysql中选择5行

我希望它出来1 - 5,我想它如果你只需要选择从5行显示的名称

$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]; 

    } 
+0

不要有为什么我寻求帮助,这就是任何你 – Rickstar

回答

3

我认为OP希望五行,而不是列。下面是正确的代码,假设你已经有一个MySQL连接打开:

$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); 
0

MySQL你可以这样做:

SELECT * 
    FROM Table 
ORDER BY column 
LIMIT 5 
+2

可能希望修改这个... LIMIT 100!= 5行... – Buggabill

+0

权,好赶上:) –

0

从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 
?> 
0

尝试使用MySQL的LIMIT子句来限制你的结果为5行。并使用PHP的mysql_fetch_assoc()(返回一个关联数组)而不是mysql_fetch_row()(返回一个数字索引的数组)。另外,最好使用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);