Selecting MySql table data into an array

2019-03-20 16:55发布

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

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

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.

4条回答
Lonely孤独者°
2楼-- · 2019-03-20 17:11
$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 />";
}
查看更多
家丑人穷心不美
3楼-- · 2019-03-20 17:15
   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";
}
查看更多
Emotional °昔
4楼-- · 2019-03-20 17:16

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>";
?>
查看更多
聊天终结者
5楼-- · 2019-03-20 17:26
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 />";
}
查看更多
登录 后发表回答