【问题标题】:Return the number of rows with MySQLi使用 MySQLi 返回行数
【发布时间】:2014-12-18 16:51:26
【问题描述】:

我正在尝试返回在我的数据库中找到的行数。第一次使用 php mvc 框架对我来说很新(就像 php 一样)。

我的查询工作正常,数据在表中按预期显示。

我不太确定我应该把代码放在哪里?我一直在查看mysqli_num_rows()mysqli_stmt_num_rows()PDOStatement::rowCount() - 如果有的话,我应该使用哪一个?

我只想显示

我们找到了 x 条记录!

到目前为止我的代码;

型号

public function categoryView()
{
    $sth = $this->db->prepare("SELECT 
    id, 
    title,
    FROM book 
    WHERE status != 'Archive' AND category='" . mysql_real_escape_string($_GET['category']) . "' ORDER BY id DESC LIMIT 15");

    $sth->execute();

    $all_books = array();

    foreach ($sth->fetchAll() as $book) {

        $all_books[$book->id] = new stdClass();
        $all_books[$book->id]->id = $book->id;
        $all_books[$book->id]->title = $book->title; 
    }
    return $all_books;
}

查看

foreach ($this->books as $book) {
    echo "<tr>";
    echo '<td>'.$book->id.'</td>';
    echo '<td>'.$book->title.'</td>';
    echo "</tr>";
}

【问题讨论】:

  • 你可以使用 --> $sth->execute(); $result = $sth->$sth->fetchAll(); $countRows = $sth->num_rows;这比正常计数要快

标签: php pdo mysqli


【解决方案1】:

我们需要更正您的部分代码。首先,mysql() 函数已长期贬值,不应使用,尤其是mysql_real_escape_string()。相反,您需要do a little bit of reading about PDO bound values。我从您提供的代码中看到的布局和默认值猜测您可能已经在 PHP-Mini(即 PDO)上构建了您的系统,尽管考虑到我看到 $sth-&gt;execute(); 它绝对是 PDO,所以您的查询应该是:

$sql = "SELECT id, title "
     . "FROM book "
     . "WHERE status != 'Archive' AND category = :cat "
     . "ORDER BY id DESC LIMIT 15";
$sth = $this->db->prepare($sql);
$sth->bindValue(':cat', $_GET['category']);
$sth->execute();

然后,要返回计数,因为 PDO::rowCount() 的行为对于 select 语句是不可预测的,请使用

$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return count($result);

虽然您接受的答案确实有效,但出于安全和最佳实践原因,我建议您进行上述更改(至少对查询进行更改)。

【讨论】:

  • @johnny_s 这也是最糟糕的做法。
  • “因为 PDO::rowCount() 的行为对于 select 语句是不可预测的”
  • @ircmaxell If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications. 直接来自 PHP.net 手册。它可能适用于大多数 MySQL 安装,但我们中的一些人也使用 MSSQL、Postgre 和 Oracle 等。在那里效果不佳。
  • @tereško 比使用已弃用的 Mysql() 函数和直接将未经处理的变量放入查询中更糟糕?
  • @iamgory 我在哪里添加您在模型/视图中提供的代码?我认为它正在工作,但在进一步测试时它不是。我收到一个通知:未定义变量:导致我在第 47 行查看(此行是 Found records)
【解决方案2】:

在你看来,捷径是这样的:echo count($this->books);

另一种方法是将值推送到控制器中的数组中: return array('books' => $all_books, 'row_count' => count($all_books));

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2016-05-17
    • 2012-11-02
    相关资源
    最近更新 更多