php mysql 获取数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5729955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql fetch array
提问by Richard
I am trying to do a fetch array which pulls out 4 rows and each row has 2 columns. Is there anyway I can define each individual field in each row as a variable individually?
我正在尝试做一个提取数组,它拉出 4 行,每行有 2 列。无论如何,我可以将每一行中的每个单独字段定义为一个变量吗?
row 1 name, id
row 2 name, id
row 3 name, id
row 4 name, id
<?php echo $row1name;?>
<?php echo $row1id;?>
<?php echo $row2name;?>
<?php echo $row2id;?>
<?php echo $row3name;?>
<?php echo $row3id;?>
<?php echo $row4name;?>
<?php echo $row4id;?>
Does this make sense?
这有意义吗?
回答by Nicola Cossu
$r = array();
$query = mysql_query("select id,name from table");
while ($row = mysql_fetch_assoc($query)) {
$r[] = $row;
}
echo $r[1]['name'];
echo $r[3]['id'];
and so on.
等等。
You can do
你可以做
echo '<pre>';
print_r($r);
if you want to see the content of your array.
如果您想查看数组的内容。
回答by Jon Skarpeteig
To access the fields in separate rows, you can do something like this:
要访问单独行中的字段,您可以执行以下操作:
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "ID: ".$row[0];
echo "NAME: ".$row[1];
}