2009-10-23 116 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);