Laravel不能使用mysql_fetch_array()

时间:2016-11-23 14:26:27

标签: php mysql laravel query-builder

尝试在Laravel中使用mysql_fetch_array()时出错。

while ($row = mysql_fetch_array($query))

使用什么而不是mysql_fetch_array()?

我遇到错误,

  

mysql_fetch_array()期望参数1是资源,给定数组

完整部分,

//prepare the tag cloud array for display
    $terms = array(); // create empty array
    $maximum = 0; // $maximum is the highest counter for a search term

    $query = DB::select('SELECT term, counter FROM search ORDER BY counter DESC LIMIT 30');

    while ($row = mysql_fetch_array($query))
    {
        $term = $row['term'];
        $counter = $row['counter'];

        // update $maximum if this term is more popular than the previous terms
        if ($counter > $maximum) $maximum = $counter;

        $terms[] = array('term' => $term, 'counter' => $counter);

    }

2 个答案:

答案 0 :(得分:4)

DB语句和选择返回结果,而不是查询对象,因此您只需要遍历结果。

$results = DB::select('SELECT term, counter FROM search ORDER BY counter DESC LIMIT 30');

foreach($results as $row)
{
    $term = $row->term;
    $counter = $row->counter;

    // update $maximum if this term is more popular than the previous terms
    if ($counter > $maximum) $maximum = $counter;

    $terms[] = array('term' => $term, 'counter' => $counter);

}

有关通过数据库类运行原始查询的更多信息,请参见here

答案 1 :(得分:-1)

由于使用了关联数组从数据库中提取数据,因此您还可以在mysql_fetch_array()中指定一个标志,即MYSQL_ASSOC。

<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result,MYSQL_ASSOC));
mysql_close($con);
?>

有关更多详细信息,请尝试:http://w3schools.sinsixx.com/php/func_mysql_fetch_array.asp.htm