简体   繁体   English

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

[英]PHP Count array index and convert integer to string

I got an array taken from an mysqli query, this array contain a list of tasks.我从 mysqli 查询中获取了一个数组,该数组包含一个任务列表。 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.使用此代码,我得到一个 int(2) 响应,该数组包含 5 个元素,我不知道它需要“2”的位置,即使我必须将其转换为数字。

Thanks in advice for help!感谢您的建议帮助!

*sigh*

You need to use count() function in mysql.您需要在 mysql 中使用count()函数。 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.您不需要选择 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM