简体   繁体   中英

How to loop through with mySQL query to return an array

I'm still very new to SQL and I've managed to grab the data I want using a query. I want to be able to select the sum of records on a day and I can access it from PHP using

<?php 
    $sql = $pdo->prepare("select count(*) from `Visits` where 
    date(`Date`)=date(date_sub(now(),interval 1 day))");
    $sql->execute();
    $result = $sql->fetch(PDO::FETCH_ASSOC);
    echo $result['count(*)'];
?>;

The data returns yesterdays records. The problem is I want to be able to do this for a set number of days (last 7 and last 30), and don't see it as feasible to repeat the above code that many times.

Any help on tweaking the query to return a single array that I could grab all those values would be really helpful! It would be ideal if the array could take the value 'number of days ago' and return the amount of records on that day.

Edit: I still need it to return 0 for days that don't have no records.

You could try it with timestamps:

<?php 
    $last_days = 7;
    $sql = $pdo->prepare("select count(*) as count from `Visits` where 
    UNIX_TIMESTAMP(`Date`) < UNIX_TIMESTAMP() AND UNIX_TIMESTAMP(`Date`) > UNIX_TIMESTAMP() - 60 * 60 * 24 * $last_days");
    $sql->execute();
    $result = $sql->fetch(PDO::FETCH_ASSOC);
    echo $result['count'];
?>;

If you want a table with the results per day, you need to modify your SQL query to return a table with both the Day and Count for each day. For that include the date as another column and group your results by the day.

<?php 
    $last_days=7
    $sql = $pdo->prepare("select count(*) as `count`,date(`Date`) as `day` from `Visits` where 
    date(`Date`) > date(date_sub(now(),interval ? day)) GROUP BY date(`Date`)");
    $sql->execute(array($last_days));
    while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
       echo $result['count']. " for day:" . $result['day']." <br>\n";
    }
    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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