1

我在 php 中创建了一个页面,我想在用户输入 weektable.php 时显示它应该显示所有值,即它应该执行这个查询

 $sql = "SELECT * FROM `battery`";

以上查询显示所有值。

当用户输入 url weektable.php?sort=w 它应该执行这个查询

 $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";

以上查询显示当前日期和日期前一周之间的值。

但我不知道该怎么做。我想在不转到另一个页面的情况下执行此操作,即我想在同一页面中显示两个值

下面是我的PHP代码:

<?php
$hostdb = 'localhost';
$namedb = 'my_db';
$userdb = 'root';
$passdb = 'root';

try {

  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8


$currDate = date('Y-m-d H:i:s');
$date = $currDate ;
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
//$offset = $dow - 3;
$offset = $dow - date('d');
if ($offset < 0) {
    $offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 1; $i++, $ts += 86400){
    //print date("Y-m-d l", $ts) ."</br>" . "\n";
$week = date("Y-m-d H:i:s", $ts) ."</br>";

}

        $sql = "SELECT * FROM `battery`";
        $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";


  $result = $conn->query($sql);

echo "<table border='1' style='font-family:arial;font-size12px;' cellspacing=1>
<tr>
<th>User Id</th>
<th>Firstname</th>
<th>LastName</th>
<th>EmailId</th>
<th>Date</th>
</tr>";

  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
  echo "<tr>";

  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['emailid'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";

  echo "</tr>";
  }

echo "</table>";

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();

}

?>

请我需要帮助。任何帮助将不胜感激。

4

2 回答 2

0
if (isset($_GET["sort"])) {
  if ($_GET["sort"] == "w") {
    $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";
  }
}else{
    $sql = "SELECT * FROM `battery`";
}

我假设您正在请求此页面,例如:

./weektable.php?sort=w

我也有点懒惰,应该添加为 isset($_GET["sort"]) - 我已经编辑了上面的代码示例.....编辑抱歉,IRL 变得非常匆忙,我希望这会有所帮助。感谢那些指出早期错误的人。

于 2013-05-08T11:41:09.647 回答
0

为第二个查询定义不同的变量。例如$sql_range = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";,然后在单独的变量中为其获取结果$result2 = $conn->query($sql_range );

我希望这能解决你的问题。

于 2013-05-08T11:39:17.043 回答