dtlh12053 2015-09-15 15:17
浏览 86
已采纳

PHP Count数组索引并将整数转换为字符串

I got an array taken from an mysqli query, this array contain a list of tasks. I must to count how many tasks is in the array ( so only the number of row ) and put in a icon badge as a human readable number.

     try {
    $db = new PDO("mysql:host=127.0.0.1;dbname=c9", "andreaem_dev", "");

    //echo "Connected to database<br/>"; // check for connection

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

    $sql = "SELECT ID FROM data_tasks WHERE data_tasks . user = 'admin'"; //I'm selecting ID so only one element on the row is count
    $result = $db->query($sql);
    foreach ($result as $row) {

            $row = $result->fetch(PDO::FETCH_NUM);
            echo $row[0];
        }

    $db = null; // close the database connection

}

catch(PDOException $e) {
    echo $e->getMessage();
}

With this code i get a int(2) response, the array contains 5 element and i don't know where it takes '2', even i must to convert it in a number.

Thanks in advice for help!

  • 写回答

1条回答 默认 最新

  • doushengyou2617 2015-09-15 15:52
    关注

    *sigh*

    You need to use count() function in mysql. this is how databases intended to work: they count your data for you. You don't need to count by hand. You don't need to select id. You don't need to loop over results. You don't need to convert number to string. You just have to ask database to count and then get the result.

    $db = new PDO("mysql:host=127.0.0.1;dbname=c9", "andreaem_dev", "");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT count(*) FROM data_tasks WHERE user = 'admin'";
    $count = $db->query($sql)->fetchColumn();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?