douzhao9608 2018-04-03 02:50
浏览 43
已采纳

PHP MySQL - 作为整数的记录数

I'm trying to get the number of records in my database as an integer and use it in PHP to set certain conditions. My code consists of the following:

$sql = "SELECT COUNT(id) FROM sql_table";
$records = $conn->query($sql);
$record_count = $records->fetch_assoc();

I did a var_dump of $record_count and it returned an array: array(1) { ["COUNT(id)"]=> string(1) "4" }. What I can't do is just access the number 4. I can access string(1) "4" by accessing $record_count['COUNT(id)'], but I can't find a way to access the number 4. If I try indexing, as in $record_count['COUNT(id)'][11], I get nothing. This value does not appear to be a straight string. How can I access the number of records in the table as an integer for use in PHP?

  • 写回答

1条回答 默认 最新

  • duanchi8836 2018-04-03 02:53
    关注

    You can do it this way, but it's better to either use the internal num_rows in my opinion, or to do bind_result() to access COUNT(id) instead of using fetch assoc. That's just my style though :) This should work just fine for you.

    $query = $sql->prepare("SELECT id FROM sql_table");
    $query->execute();
    $query->store_result();
    $results = $query->num_rows;
    $query->close();
    
    echo $results;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等