php 如何在数组中存储mysql数据的行/列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4697515/
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
How to store row/column of mysql data in array
提问by Matt Lowden
I want to be able to store (not echo) some data that has been selected from a mysql database in a php array. So far, I have only been able to echo the information, I just want to be able to store it in an array for later use. Here is my code:
我希望能够在 php 数组中存储(而不是回显)从 mysql 数据库中选择的一些数据。到目前为止,我只能回显信息,我只是希望能够将其存储在一个数组中以备后用。这是我的代码:
$query = "SELECT interests FROM signup WHERE username = '$username'";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
echo $row['interests'];
echo "<br />";
}
回答by Matt Lowden
You could use
你可以用
$query = "SELECT interests FROM signup WHERE username = '".mysql_real_escape_string($username)."'";
$result = mysql_query($query) or die ("no query");
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
This will basically store all of the data to the $result_array
array.
这基本上会将所有数据存储到$result_array
数组中。
I've used mysql_fetch_assoc
rather than mysql_fetch_array
so that the values are mapped to their keys.
我使用mysql_fetch_assoc
而不是mysql_fetch_array
将值映射到它们的键。
I've also included mysql_real_escape_string
for protection.
mysql_real_escape_string
为了保护,我也包括在内。
回答by coreyward
You can "store" it by not accessing it from the result set until you need it, but if you really want to just take it and put it in a variable…
您可以通过在需要之前不从结果集中访问它来“存储”它,但是如果您真的只想获取它并将其放入变量中......
$query = "SELECT interests FROM signup WHERE username = '$username'";
$result = mysql_query($query) or die ("no query");
$interests = array();
while(false !== ($row = mysql_fetch_assoc($result))) {
$interests[] = $row;
}