2011-01-18 57 views
6

我嘗試從mysql捕獲數據以將它們全部放入數組中。 假設:選擇MySql表數據到數組

users table 
    ----------------------- 
    id| name | code 
    ---------------------- 
    1| gorge | 2132 
    2| flix | ksd02 
    3| jasmen | skaod2 

    $sql = mysql_query("select id, name, code from users"); 
    $userinfo = array() 
    while($row_user = mysql_fetch_array($sql)){ 
    $userinfo = $row_user[name] 
    } 
------------------------- 
foreach($userinfo as $usinfo){ 
echo $usinfo."<br/>"; 
} 

這裏的問題是,我只能用戶信息陣列中插入用戶名,但不能同時插入代碼& ID,請幫我插入同一陣列中的所有數據。

[P.S]請不要面向對象。

+0

更新了我的答案,這有幫助嗎? – 2011-01-18 21:53:45

回答

28
$sql = mysql_query("select id, name, code from users"); 
$userinfo = array(); 

while ($row_user = mysql_fetch_assoc($sql)) 
    $userinfo[] = $row_user; 

這會給你$userinfo與以下結構的陣列:

[ 
    [id => 1, name => 'gorge', code => '2123'], 
    [id => 2, name => 'flix', code => 'ksd02'], 
    [id => 3, name => 'jasmen', code => 'skaod2'] 
] 

如果你想輸出的數據:

foreach ($userinfo as $user) { 
    echo "Id: {$user[id]}<br />" 
     . "Name: {$user[name]}<br />" 
     . "Code: {$user[code]}<br /><br />"; 
} 
+0

那是不是我所問的請求再次讀我的曲譜 – 2011-01-18 21:41:48

+0

我敢肯定,你輸入這個非常快,但你使用mysql_query兩次。這是行不通的。 – Christa 2011-01-18 21:43:46

+0

@克里斯塔,哎呀! – jasonbar 2011-01-18 21:44:26

4
while($row_user = mysql_fetch_assoc($sql)){ 
    $userinfo[] = $row_user; 
} 

foreach($userinfo as $usrinfo){ 
    echo "Id: ".$usrinfo['id']."<br />"; 
    echo "Name: ".$usrinfo['name']."<br />"; 
    echo "Code: ".$usrinfo['code']."<br />"; 
} 
-4
while($row_user = mysql_fetch_array($sql)){ 
    $row_id = $row_user ["id"]; 
     $row_author = $row_user ["author"]; 
     $row_code = $row_user ["code"]; 
     $userinfo[] = array("id"=> $row_id , "author"=> $row_author, "code"=> $row_code); 
    } 
foreach ($userinfo as $user) { 
    echo "Id: {$user[id]}\n" 
     . "Name: {$user[name]}\n" 
     . "Code: {$user[code]}\n\n"; 
} 
3

我發現這段代碼和我節省了我的一天:

<?php 
$sql=mysql_query("select * from table1"); 

/*every time it fetches the row, adds it to array...*/ 
while($r[]=mysql_fetch_array($sql)); 

echo "<pre>"; 
// Prints $r as array 
print_r ($r); 
echo "</pre>"; 
?>