我尝试从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/>";
}
这是问题我只能插入用户名但不能插入代码&amp; userinfo数组中的id请帮我在同一个数组中插入所有数据。
[P.S]请不要面向对象。
答案 0 :(得分:31)
$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 />";
}
答案 1 :(得分: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 />";
}
答案 2 :(得分:4)
我发现了这段代码,我节省了一天的时间:
<?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>";
?>
答案 3 :(得分:-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";
}