2017-03-11 89 views
0

我试图从两个日期之间的数据库中获取行。我在这里用了其他一些问题来说明这一点,但我不知道如何从这里前进。使用PHP在SQL中的两个日期之间选择行

下面是代码,下面是输出和在SQL中运行查询的照片的屏幕截图。

感谢您的帮助!

-

的代码该第一部分输出ID,姓名等

<?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(); 

?> 

的代码输出 “0结果”

<?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.

编辑:我把代码写入第二代码块的IF ELSE语句的问题时犯了一个错误。我只是将其更新为我在网站上实际拥有的内容。我没有根据解决方案改变任何东西,但仍然没有得到要打印的行。

+1

',而(){}其他{}'是无效的PHP。 – jhmckimm

回答

0

您的结果已列出 - 正如您从屏幕截图中看到的那样。问题:Whileelse一起没有意义。

您的最后一个例子是缺少}所以它说:while { } else { echo "0 results"}

echo "0 results"应进行相关的num_rows -check,不以while

+0

'while(){} else {}'无效。没有缺少'}'。这只是一个嵌套问题。 – jhmckimm

+0

嘿,你好,谢谢你的回复。我为这个问题粘贴了我的代码时犯了一个错误。它现在更新了第二部分到我在网站上实际拥有的内容。 else语句现在应该与if语句关联,并且我仍然输出“0结果” –

0

你做得对,除了使用while/else; 您的代码(2-ND)部分应该是这样的:

if ($result->num_rows > 0) { 

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

    //Say that there's 0 results 
} 
+0

谢谢。我为这个问题粘贴了我的代码时犯了一个错误。它现在更新到我在网站上实际拥有的内容。我刚刚尝试了您发布的代码,并仍在输出“0结果”。 –

相关问题