【问题标题】:Laravel cannot use mysql_fetch_array()Laravel 不能使用 mysql_fetch_array()
【发布时间】:2016-11-23 14:26:26
【问题描述】:

尝试在 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);

    }

【问题讨论】:

  • 添加完整的东西
  • 为什么?你为什么要这样做???只需改用DB 函数
  • 这里如何使用DB功能? DB::??

标签: php mysql laravel query-builder


【解决方案1】:

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);

}

有关通过 DB 类运行原始查询的更多信息,请访问here

【讨论】:

  • 现在它会生成一个错误,因为 AdminViewController.php 第 84 行中的 FatalErrorException:不能使用 stdClass 类型的对象作为数组。第 84 行是“$term = $row['term'];”
  • 啊,我不记得它是对象还是数组,我认为它在 4 和 5 之间变化。我会用它作为对象更新我的答案。
  • 是的,现在它正在工作!我是 laravel 的新手。这就是为什么我没有注意到他们。谢谢! :)
  • 哦,我之前试过,但他们让我等 6 分钟。完成!
  • 不会将所有结果返回到 var DB::select?
【解决方案2】:

由于您使用关联数组从数据库中提取数据,您还可以在 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

【讨论】:

  • 警告: mysql_* 扩展自 PHP 5.5.0 起已弃用,自 PHP 7.0.0 起已被删除。相反,应该使用mysqliPDO_MySQL 扩展名。在选择 MySQL API 时,另请参阅 MySQL API Overview 以获得更多帮助。
猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2014-05-20
  • 1970-01-01
  • 2011-11-10
  • 2011-07-16
  • 1970-01-01
相关资源
最近更新 更多