【问题标题】:Select from database and store in an array从数据库中选择并存储在数组中
【发布时间】:2011-10-10 20:03:47
【问题描述】:

我想从 db 中选择一些数据并存储在一个数组中。假设我的数据库表中有一个“关键字”列。我想选择关键字列类似于“自然”的所有行。

我正在尝试以下代码:

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

    ?>

所以 db 的结果应该只返回一个关键字“nature”,我需要将其存储在数组中。

  1. 为什么要存储相同的字符串两次? db 中没有任何其他行与术语性质相似。
  2. 为什么它只存储数组中的第一个字母?它不应该存储“nature”而不是“n”吗?

请帮我解决这个问题。

【问题讨论】:

    标签: php mysql arrays select


    【解决方案1】:

    应该是这样的

    $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

      【讨论】:

        猜你喜欢
        • 2015-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多