【问题标题】:How would I go about returning the number of rows using the COUNT() function in a MySQL query? [duplicate]我将如何在 MySQL 查询中使用 COUNT() 函数返回行数? [复制]
【发布时间】:2016-12-12 22:39:25
【问题描述】:

我正在尝试验证我的查询是否从数据库中获取了至少 1 行。

$db = new SQLite3('../portfolio.db');

$results = $db->prepare('SELECT COUNT(*) FROM users WHERE id = :id');
$results->bindValue(':id', 7);

$grab = $results->execute();

if([COUNT(*) VALUE] == 1) {
    echo "true";
}

我想弄清楚的是,我可以用 if 语句中的 [COUNT(*) VALUE] 替换什么来回显“true”。

有人知道这是怎么做到的吗?我认为有一种方法可以返回 COUNT(*) 的数量,但我不完全确定。

与我类似的问题很可能不起作用,因为他/她使用的是常规 mysql/php,而这是 PHP PDO 和 SQLite3。

【问题讨论】:

  • 为什么用sqlite3mysql标记?
  • @shmosel 因为它使用的是 SQLite3 和 MySQL。
  • 我很确定你也需要获取:$row = $grab->fetchArray(SQLITE3_ASSOC);`

标签: php sqlite


【解决方案1】:

在查询中使用别名

$db = new SQLite3('../portfolio.db');

$results = $db->prepare('SELECT COUNT(*) as count FROM users WHERE id = :id');
$results->bindValue(':id', 7);

$results->execute();//execute method just return true or false so no need to use variable here

if($results->fetch()['count'] == 1) {//you need to fetch() first row and column name (in this case is alias "count")
    echo "true";
}

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2011-12-18
    • 2011-09-02
    • 2015-02-27
    相关资源
    最近更新 更多