开发者

Selecting MySql table data into an array

I try to catch data from mysql to put them all in array. Suppose:

    users table
    -----------------------
    id| name | code 
    ----------开发者_JAVA技巧------------
    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/>";
}

Here is the problem i can only insert user name but cant insert also code & id in userinfo array please help me to insert all data in same array.

[P.S] No object oriented please.


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

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

This will give you $userinfo as an array with the following structure:

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

If you want to output the data:

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


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 />";
}


I found this code and I save my day:

<?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>";
?>


   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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜