I have created a page in php I want to show when user type in weektable.php it should show all the value i.e it should execute this query
$sql = "SELECT * FROM `battery`";
above query display all the value.
and when user type in url weektable.php?sort=w it should execute this query
$sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";
above query display value between current date and one week before date.
But I have no Idea how to do it. I want to do it without go to another page i.e I want show both the value in same page
Below is my PHP code:
<?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>" . "
";
$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();
}
?>
Please I need help. Any Help will be greatly appreciated.
Define a different variable for second query. such as $sql_range = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";
and then fetch results for it in a separate variable $result2 = $conn->query($sql_range );
I hope that should solve your question.
if (isset($_GET["sort"])) {
if ($_GET["sort"] == "w") {
$sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";
}
}else{
$sql = "SELECT * FROM `battery`";
}
I'm assuming that you are requesting this page with something like:
./weektable.php?sort=w
I was also a bit lazy and should have added as isset($_GET["sort"]) - I have edited the code sample above..... EDIT sorry become very rushed IRL, I hope this helps. Thanks to those that pointed out earlier error.