2011-07-22 82 views
1

我想从数据库中选择一些数据并将其存储在数组中。假设我的数据库表中有一列“关键字”。我想选择关键字列就像“自然”的所有行。从数据库中选择并存储在数组中

我想下面的代码:

<? 
    $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) 

    ?> 

因此,从数据库的结果应该只返回一个关键词“自然”,我需要在阵列来存储。

  1. 为什么它存储相同的字符串两次?数据库中没有任何类似于术语“自然”的其他行。
  2. 为什么它只在数组中存储第一个字母?它不是存储“自然”而不是“n”?

请帮我解决这个问题。

回答

3

应该像

$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' ]; 
} 

在您的解决方案,你只能取从第一个记录结果集的数字索引数组。

顺便说一句 - 你知道一个以通配符开头的LIKE查询不能使用任何索引?

2

使用mysql_fetch_assoc代替mysql_fetch_array

相关问题