简体   繁体   中英

Selecting rows between two dates in SQL with PHP

I'm trying to get rows from my database between two dates. I've used other questions here to get to this point, but I don't know how to move forward from here.

Here is the code, and underneath are the screenshots of the output and a photo running the query in SQL.

Thanks for the help in advance!

--

This first section of code outputs the ID, name, etc.

<?php

$sql = "SELECT * FROM songs ";
$result = $link->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["ID"] . " - Name: " . $row["name"] . " " . $row["released"]. "<br>";
}
} else {
    echo "0 results";
}

/* close connection */    

$link->close();

?>

This section of code outputs "0 Results"

<?php

$from_date = '2015-01-01';
$to_date = '2017-04-04';

$sql = "SELECT * FROM songs WHERE released BETWEEN '" . $from_date .  "' AND '" . $to_date . "' ";
$result = $link->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["ID"] . " - Name: " . $row["name"] . " " . $row["released"]. "<br>";
    }
} else {
    echo "0 results";
}

/* close connection */    

$link->close();

?>

This is what the page looks like with the above code.

I've successfully selected the rows in SQL.

EDIT: I made a mistake when writing the code into the question for the IF ELSE statement on the 2nd block of code. I just updated it to what I actually have on the site. I didn't change anything based on the solutions, and am still not getting the rows to print.

Your results are listed - as you can see from your screenshot. Problem: While along with else does not make sence.

your last example is missing a } so it says: while { } else { echo "0 results"}

But the echo "0 results" should be related to the num_rows -check, not to the while .

You done everything right, except using while/else ; Your code (2-nd) section should look like this:

if ($result->num_rows > 0) {

  while () {
     //print your rows
  }
} else {

  //Say that there's 0 results
}

Ah man, I just needed to had to comment out this line from the first block:

$link->close();

I apologize to everyone who answered if it wasn't clear that the blocks of code followed one another. Anyways, for anyone else with the same problem, don't close the connection -_-

Here's what is output when I comment out the line from the first block

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