php 从数据库中选择并存储在数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6786788/
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
Select from database and store in an array
提问by Roman
I want to select some data from db and store in an array. Suppose I have a column "keyword" in my db table. I want to select all rows where keyword column is like "nature".
我想从数据库中选择一些数据并存储在一个数组中。假设我的数据库表中有一个“关键字”列。我想选择关键字列类似于“自然”的所有行。
I am trying following code:
我正在尝试以下代码:
<?
$term= "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
$rows = mysql_fetch_array($result);
foreach ($rows as $row){
array_push($arr, $row['keyword']);
}
print_r($arr); //output: Array ( [0] => n [1] => n )
?>
So the result from db should return only one keyword 'nature' which i need to store in array.
所以 db 的结果应该只返回一个我需要存储在数组中的关键字 'nature'。
- Why it is storing same string two times? There is no any other row in db similar to the term nature.
- Why it is storing only first letter in the array? Shouln't it store "nature" instead of "n"?
- 为什么它两次存储相同的字符串?db 中没有任何其他行类似于术语自然。
- 为什么它只存储数组中的第一个字母?它不应该存储“自然”而不是“n”吗?
Please help me fixing this.
请帮我解决这个问题。
回答by wonk0
Should be something like
应该是这样的
$term = "nature";
$arr = array();
$sql = "select keyword from keywords where keyword LIKE '%$term%'";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
arr[] = $row[ 'keyword' ];
}
In your solution you only fetch the first record from the result-set as numeric indexed array.
在您的解决方案中,您只从结果集中获取第一条记录作为数字索引数组。
Btw - you are aware that a LIKE-query starting with a wildcard cannot make use of any index?
顺便说一句 - 您知道以通配符开头的 LIKE 查询不能使用任何索引吗?
回答by rabudde
use mysql_fetch_assoc
instead of mysql_fetch_array
使用mysql_fetch_assoc
代替mysql_fetch_array