Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select count(*) from database

Tags:

php

mysql

pdo

I have this SQL query which is working as it should when I run it into phpMyAdmin.

SELECT COUNT( * ) , LENGTH( Number ) AS Numbers
FROM  `history_2015-07-22` 
WHERE Number NOT LIKE  '123%'
OR LENGTH( Number ) <50
GROUP BY Numbers
ORDER BY TIME =  '2015-07-22 00:00:01' ASC 

I want now to make a simple php page where I want to display the query results on the browser but I can't figure out how to echo it exactly. So i've made this:

$result = $pdo->prepare("SELECT COUNT( * ) , LENGTH( Number ) AS Numbers
                         FROM  `history_2015-07-22` 
                         WHERE Number NOT LIKE  '123%'
                         OR LENGTH( Number ) <50
                         GROUP BY Numbers
                         ORDER BY TIME =  '2015-07-22 00:00:01' ASC ");
$result->execute();
foreach ($result as $Numbers)
{
    echo '<div class="container">
                '.$Numbers['COUNT(*)'].'
                '.$Numbers['LENGTH(Number)'].'
          </div>';
}

What I want to echo is Count and Length. I'm sure is something very simple what I miss but can't figure it out.

like image 888
John Avatar asked Jul 16 '26 07:07

John


2 Answers

First, can you please explain what you're trying to do exactly with the SQL query?

From what I understand, you can try this:

$result = $pdo->prepare("SELECT COUNT( * ) AS ct_all, LENGTH( `Number` ) AS Numbers
                         FROM  `history_2015-07-22` 
                         WHERE `Number` NOT LIKE ('123%')
                         AND Numbers < 50
                         GROUP BY Numbers
                         ORDER BY `TIME` ASC");
$result->execute();
$results = $result->fetchAll();
foreach ($results as $row) {
    echo '<div class="container">';
    echo $row['ct_all'] . ' // ';
    echo $row['Numbers'];
    echo '</div>';
}
like image 102
x3ns Avatar answered Jul 18 '26 21:07

x3ns


$result = $pdo->prepare("SELECT COUNT( * ) as cnts, LENGTH( Number ) AS num
                         FROM  `history_2015-07-22` 
                         WHERE Number NOT LIKE  '123%'
                         OR LENGTH( Number ) <50
                         GROUP BY num
                         ORDER BY TIME =  '2015-07-22 00:00:01' ASC ");
$result->execute();
foreach ($result as $Numbers)
{
    echo '<div class="container">
                '.$Numbers['cnts'].'
                '.$Numbers['num'].'
          </div>';
}
like image 41
Himanshu Upadhyay Avatar answered Jul 18 '26 19:07

Himanshu Upadhyay