简体   繁体   English

php pdo在特定日期获取数据返回空结果

[英]php pdo fetch data on specific date return empty result

I have a problem to return query based on a specific date that input in variable $now 我有一个问题要根据在变量$now中输入的特定日期返回查询

Below is my code: 下面是我的代码:

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
// bind column to variable
//Connect to DB
$host = "localhost"; //Host Name
$port = '3306'; //Default MySQL Port
$dbname = "mama"; //Database Name
$db_username = "root"; //MySQL Username
$db_password = ""; //MySQL Password

$dsn = "mysql:host=$host;port=$port;dbname=$dbname"; //Data Source Name = Mysql
$db = new PDO($dsn, $db_username, $db_password); //Connect to DB

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
  $now = "2014-01-01";

  //foreach ($query=$db->query("SELECT * FROM log WHERE log_datetime <= :now") as $row) {print_r($row);}
  $query->bindParam(':now', $now, PDO::PARAM_STR);
  $success = $query->execute();
}
// Catch any exception thrown
catch (PDOException $e) {
  echo "Error: " . $e->getMessage();
  // Exit, redirect, whatever you need to do.
}
$rows = $query->fetchAll(PDO::FETCH_OBJ);

?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
table, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
<title>Test</title>
</head>

<body>

<table>
    <th>Id</th>
    <th>DOB</th>
    <th>Visit</th>
    <th>Qty</th>
    <th>Amount</th>
<?php
// Use a foreach over $rows
foreach ($rows as $row) {

    // Using htmlspecialchars() on these as good practice for HTML escaping
    // Since they were fetched via FETCH_OBJ access them as properties with ->
    echo '<tr>';
    echo '<td>' . htmlspecialchars($row->log_id) . '</td>';
    echo '<td>' . htmlspecialchars($row->dob) . '</td>';
    echo '<td>' . htmlspecialchars($row->log_datetime) . '</td>';
    echo '<td>' . htmlspecialchars($row->log_count) . '</td>';
    echo '<td>' . htmlspecialchars($row->amount) . '</td>';
    echo '</tr>';
}

?>
</table>
</body>
</html>

I would like the result to show on the specific date set, but it returns nothing except the table header. 我希望结果显示在特定的日期集上,但是除了表头外,它什么也不返回。

Additional info, my log_datetime use DATETIME mysql format. 附加信息,我的log_datetime使用DATETIME mysql格式。

I did some SO search but non of the question or answer posted in SO can help my question. 我进行了一些SO搜索,但SO中张贴的问题或答案都无法帮助我解决问题。 Please advise where did I go wrong, I followed the php PDO tutorial but it seems not working. 请告知我哪里出了问题,我遵循了php PDO教程,但似乎无法正常工作。

You have one small mistake in your SQL syntax: 您的SQL语法有一个小错误:

SELECT * FROM log WHERE log_datetime <= ?
// ----------------------------------^

The error is in the sql syntax, try changing "SELECT * FROM log WHERE log_datetime = < ?" 错误是在sql语法中,请尝试更改"SELECT * FROM log WHERE log_datetime = < ?" with "SELECT * FROM log WHERE log_datetime <= ?" "SELECT * FROM log WHERE log_datetime <= ?"

As you begin to get your error checking in order, this will start to take shape in a meaningful way for you. 当您开始按顺序进行错误检查时,这将以对您有意义的方式开始形成。

Your query execution is correct, and the SQL statement itself should return the expected values. 您的查询执行是正确的,并且SQL语句本身应返回期望值。 Your problem still lies in an incorrect transfer of values from the fetched $row to their final positions in the <td> tags. 您的问题仍然在于从获取的$row<td>标记中最终位置的值传输不正确。

Some things to take care of: 要注意的一些事情:

  • Set PDO into ERRMODE_EXCEPTION so it throws exceptions on any error. 将PDO设置为ERRMODE_EXCEPTION以便在发生任何错误时引发异常。
  • Wrap all the database stuff in try/catch to catch any PDO exceptions 将所有数据库内容包装在try/catch以捕获任何PDO异常
  • Use htmlspecialchars() to escape all the output for HTML 使用htmlspecialchars()转义HTML的所有输出
  • It is left to you to take some appropriate action in the catch {} block 您可以在catch {}块中采取一些适当的措施

require('./inc/connection.php');

// Suggest setting PDO into ERRMODE_EXCEPTION so it throws exceptions on any error
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// With PDO in exception mode, wrap all of this in try/catch
try {
  $now = "2014-01-01";

  $query = $db->prepare("SELECT * FROM log WHERE log_datetime <= :now");
  $query->bindParam(':now', $now);
  $success = $query->execute();
}
// Catch any exception thrown
catch (PDOException $e) {
  echo "Error: " . $e->getMessage();
  // Exit, redirect, whatever you need to do.
}

// Assuming no failure (you didn't exit or redirect)
// You can build your table.

// First fetch all rows:
$rows = $query->fetchAll(PDO::FETCH_OBJ);

// Now all your rows are in the array. You're done with PDO.
echo '<table>';
echo '<tr>
<th>Id</th>
<th>DOB</th>
<th>Visit</th>
<th>Qty</th>
<th>Amount</th>
</tr>';

// Use a foreach over $rows
foreach ($rows as $row) {

    // Using htmlspecialchars() on these as good practice for HTML escaping
    // Since they were fetched via FETCH_OBJ access them as properties with ->
    echo '<tr>';
    echo '<td>' . htmlspecialchars($row->log_id) . '</td>';
    echo '<td>' . htmlspecialchars($row->dob) . '</td>';
    echo '<td>' . htmlspecialchars($row->log_datetime) . '</td>';
    echo '<td>' . htmlspecialchars($row->log_count) . '</td>';
    echo '<td>' . htmlspecialchars($row->amount) . '</td>';
    echo '</tr>';
}
echo '</table>';

// You're done.

I removed all of the inline style- attributes. 我删除了所有内联style-属性。 None of that belongs in your markup and instead should be in the CSS. 这些都不属于您的标记,而应该属于CSS。 It can all be handled with a CSS rule like: 所有这些都可以通过CSS规则处理:

table, td {
  border: 1px solid black;
  border-collapse: collapse;
}

A final note about $now : If you really plan to use the current date, there's no need for a bound parameter. 关于$now最后一点:如果您确实打算使用当前日期,则不需要绑定参数。 You can just call MySQL's CURDATE() in the statement directly: 您可以直接在语句中直接调用MySQL的CURDATE()

SELECT * FROM log WHERE log_datetime <= CURDATE()
while ($query->fetchAll()) {
    echo '<tr>';
    echo '<td style="border: 1px solid black;">' . $log_id . '</td>';
    echo '<td style="border: 1px solid black;">' . $dob . '</td>';
    echo '<td style="border: 1px solid black;">' . $log_datetime . '</td>';
    echo '<td style="border: 1px solid black;">' . $log_count . '</td>';
    echo '<td style="border: 1px solid black;">' . $amount . '</td>';
    echo '</tr>';
}

this will not fetch anything , you need to re-write it like 这不会获取任何东西,您需要像这样重新编写它

while ($row=$query->fetch(PDO::FETCH_OBJ)) {
 $log_id         = $row->log_id;
    $dob            = $row->dob;
    $log_datetime   = $row->log_datetime;
    $log_count      = $row->log_count;
    $amount         = $row->amount;

    echo '<tr>';
    echo '<td style="border: 1px solid black;">' . $log_id . '</td>';
    echo '<td style="border: 1px solid black;">' . $dob . '</td>';
    echo '<td style="border: 1px solid black;">' . $log_datetime . '</td>';
    echo '<td style="border: 1px solid black;">' . $log_count . '</td>';
    echo '<td style="border: 1px solid black;">' . $amount . '</td>';
    echo '</tr>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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