How to get past 10 days data from database using php?

I'm trying to fetch data from the last 10 days from my database. But I'm getting the error: "mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given" when I run the file on my localhost.

When I remove the where statement, it displays all the data queried successfully.

error message with where clause

result without where clause

Here is my PHP code:

<?php


                    $servername = "localhost";
                    $username = "root";
                    $password = "";
                    $dbname = "Earthquake";


                    // Create connection
                    $conn = mysqli_connect("$servername", "$username", "$password", "$dbname");
                    // Check connection
                    if (!$conn) {
                        die("Connection failed: " . mysqli_connect_error());
                    }

                    $sql = "SELECT Location, DateandTime, Magnitude FROM tbl_earthquake where  `DateandTime` >= DATE_SUB(CURDATE(), INTERVAL 10 DAY";
                    $result = mysqli_query($conn, $sql);


                    if (mysqli_num_rows($result)>0){
                        while($row = mysqli_fetch_assoc($result)){
                            echo "Location" . $row["Location"]. "-Date and Time" . $row["DateandTime"]. "Magnitude" . $row["Magnitude"]. "<br>";

                        }
                    } else{
                        echo "No results";
                    }
                    mysqli_close($conn);
                ?>

1 answer

  • answered 2018-11-08 06:34 James Shaver

    What Roy said is true, and here's another way to do it:

    <?php
    
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "Earthquake";
    
    
    // Create connection
    $conn = mysqli_connect("$servername", "$username", "$password", "$dbname");
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    
    $sql = "SELECT Location, DateandTime, Magnitude FROM tbl_earthquake where `DateandTime` BETWEEN DATE_SUB(NOW(), INTERVAL 10 DAY) AND NOW()";
    $result = mysqli_query($conn, $sql);
    
    
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo "Location" . $row["Location"] . "-Date and Time" . $row["DateandTime"] . "Magnitude" . $row["Magnitude"] . "<br>";
        }
    } else {
        echo "No results";
    }
    mysqli_close($conn);