I'm creating a simple PHP to do list. I want to turn the date red if it's not the current date. Here's part of my code, with the HTML removed:
<?php include "connection.php";?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$task = isset($_POST['task']) ? $_POST['task'] : null;
$importance = isset($_POST['importance']) ? $_POST['importance'] : null;
$due_date = isset($_POST['due_date']) ? $_POST['due_date'] : null;
$order = isset($_POST['order']) ? $_POST['order'] : null;
if(isset($task,$importance,$due_date)){
$sql = "INSERT INTO tasks (task, importance, due_date) VALUES ('$task', '$importance', '$due_date')";
$result = mysqli_query($connection, $sql);
if(!$result){
die("Database query failed.");
}
}
}
if(isset($order)){
$sql = "SELECT * FROM tasks ORDER BY {$order}";
} else {
$sql = "SELECT * FROM tasks";
}
$result = mysqli_query($connection, $sql);
if(!$result){
die("Database query failed.");
}
$current_date = date("Y-m-d");
if(isset($due_date)!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
?>
<table>
<?php
while($column = mysqli_fetch_assoc($result)){
?>
<tr><td><?php echo $column["task"]?></td><td class="<?php echo $column["importance"] ?>"><?php echo $column["importance"]?></td><td class="<?php echo $due_date_class ?>"><?php echo $column["due_date"]?></td><td><?php echo "<a href='delete_one.php?id=".$column['id']."'>Delete</a>" ?></td></tr>
<?php
}
?>
</table>
<?php include "footer.php";?>
This is the part that isn't working. It's either turning all the rows red or black, depending on what date I enter:
$current_date = date("Y-m-d");
if(isset($due_date)!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
isset($due_date)
should be changed to
$due_date
Because, isset
will return value 1
or 0
, which will be compared with date, which is going to be false
all the time.
Instead, you could do following:
if(isset($due_date))
{
$current_date = date("Y-m-d");
if($due_date!=$current_date){
$due_date_class="overdue";
} else {
$due_date_class="not_overdue";
}
}
else
{
echo "Not a valid Due Date";
}
Regarding variable scoping.
You need to declare $due_date_class
at very top, to increase its scope, otherwise you will get error. Since, scope of this variable will be limited to if
and else
.