I am making a school portal system and right now I am making the page for students to view homework. I want their homework to be highlighted in red, or not shown at all if the current date is past the due date. How can I do this?
My code for the page
<?php
//including the database connection file
include_once("connection.php");
$id= $_GET['id'];
//fetching data in descending order (lastest entry first)
$result = mysqli_query($conn, "SELECT * FROM homework where class_id= '$id'");
?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
</tr>
<?php
//while($res = mysql_fetch_array($result))
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
}
?>
</table>
</body>
Database:
Instead of a query, use a prepared statement with bind_param which is much safer. Then just compare the dates to check if $res['datedue'] passed or not. This should be it:
<?php
include_once("connection.php"); //including the database connection file
date_default_timezone_set('America/Los_Angeles'); //set the default time zone to your time zone (this is just an example)
$result = $conn->prepare("SELECT * FROM homework WHERE class_id=?");
$result->bind_param("i", (int)$_GET['id']);
$result->execute();
$result2 = $result->get_result();
?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
</tr>
<?php
while($res = $result2->fetch_array(MYSQLI_ASSOC)) {
if (date("Y-m-d") > $res['datedue']) {
echo "<tr style=\"color: red;\">";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "</tr>";
} else {
echo "<tr>";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "</tr>";
}
}
?>
</table>
</body>
You could also use $time = new DateTime; and then $time->format("Y-m-d") instead of date("Y-m-d").
More about time zones.
You should use parameterized prepared statements instead of manually building your queries.
I have used the date function to compare the dates if the date is greater then I've put some style while in else there is no style. I have gave you the idea now you can modify accordingly.
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
</tr>
<?php
//while($res = mysql_fetch_array($result))
$current_date=date("Y-m-d");
while($res = mysqli_fetch_array($result)) {
if($current_date > $res['datedue'] ){
?>
<tr style='color:red;'>;
<?php
}else {
<tr>
}
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
</tr>
}
?>
</table>
Reference
Don`t use concated raw SQL.
Use variable binding to prevent SQL injections.
<?php
$stmt = $mysqli->prepare("SELECT * FROM homework where class_id= ?");
$stmt->bind_param('i', (int)$_GET['id']); // bind vairable and cast it to integer (it is a good practice when you get data from outside)
$stmt->execute();
$result = $stmt->get_result();
while($res = $result->fetch()){
// Your code here
var_dump($res);
}
I will suggest using PDO instead of mysqli. You can read more about SQL Injections here: How can I prevent SQL injection in PHP?
Don't use select * (wildcard)
SELECT description, dateset, datedue, datedue < NOW() AS is_expired FROM homework where class_id= ?
Check the value of is_expired to see which results you will mark in red
I haven't tried the code but I guess it will work as expected
Related
right now I have a page which displays homework set by teachers from a database. The students must be able to see all their homework on this page, with the due date and set date. As of now, it's working and after the due date, the task turns red, which is fine. However, I need to now add a small box or button which can be clicked by the student once they have completed the task. Once this is done, It would delete it ONLY for the student which has clicked it.
<?php
include_once("connection.php"); //including the database connection file
$id= $_GET['id'];
$result = $conn->prepare("SELECT * FROM homework WHERE class_id=? ORDER BY datedue DESC");
$result->bind_param("i", $id);
$result->execute();
$result2 = $result->get_result();?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
<td><button type="button">Click Me!</button></td>
</tr>
<?php
while($res = mysqli_fetch_array($result2)) {
if (strtotime(date("d-m-Y")) > strtotime($res['datedue'])) {
echo "<tr style=\"color: red;\">";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "<td>".<button type=button>Click Me!</button>."</td>";
echo "</tr>";
} else {
echo "<tr>";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "<td>".<button type=button>Click Me!</button>."</td>";
echo "</tr>";
}
}
?>
</table>
</body>
How can I do this? Thank you
I couldn't test this, can you give this a try and let me know if error occurs
create new field name 'stud_completed' in homework table
homework.php page
<?php
include_once("connection.php"); //including the database connection file
$id = $_GET['id'];
$result = $conn->prepare("SELECT * FROM homework WHERE class_id=? ORDER BY datedue DESC");
$result->bind_param("i", $id);
$result->execute();
$result2 = $result->get_result();
$todayDate = strtotime(date("d-m-Y"));
$Log_student = $_SESSION['studentID'];
?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
<td>Action</td>
</tr>
<?php
while($res = mysqli_fetch_array($result2)) {
$redDueTask = null; // each loop $redDueTask will be set to NULL
$homeworkID = $res['id']; // Get the DueDate of each task
$dueDate = strtotime($res['datedue']); // Get the DueDate of each task
if ($todayDate > $dueDate) { $redDueTask = 'style="color: red;"'; } // Set $redDueTask if task has past duedate
$student_completed = explode(',',$res['stud_completed']); // get the coma seperated completed student list and convert it to array
if (!in_array($Log_student, $student_completed)) { // chk if logged in student ID is in array and if not in the list show task
?>
<tr <?php echo $redDueTask?>>
<td><?php echo $res['description']?></td>
<td><?php echo $res['dateset']?></td>
<td><?php echo $res['datedue']?></td>
<td>
<?php if (isset($redDueTask)) { // $redDueTask will bset if the task duedate has passed, so no need compelete button ?>
Time UP!
<?php } else { // $redDueTask is not set then show compelete button ?>
<button type='button'>Have Complete</button>
<?php } ?>
</td>
</tr>
<?php
}
}
?>
</table>
</body>
taskdone.php page
<?php
include_once("connection.php"); //including the database connection file
$tid = $_GET['tid']; // Get Homework Task ID from URL
$Log_student = $_SESSION['studentID']; // Get Loggedin Student ID from Session
// Get ROW Statment
$result = $conn->prepare("SELECT * FROM homework WHERE id=?");
$result->bind_param('i', $tid);
$result->execute();
$result2 = $result->get_result();
$res = mysqli_fetch_array($result2);
$stud_completed = $res['stud_completed']; // Get the current List of completed student
if ($stud_completed == "") { // If stud_completed is null or blank
$stud_completed = $Log_student; // add the current student ID with out coma
} else {
$stud_completed .= "," . $Log_student; // Inculde the current logged in student ID with coma
}
// Update ROW Statement
$sql = "UPDATE homework SET stud_completed=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $stud_completed, $tid);
if ($stmt->execute()) {
header("homework.php"); // if GOT updated go to home work task list page
}
?>
l have created an application using php,html and mysql. The application can store a user's information such as id, name, bio, and date created into the database and display in html table. The id is an auto increment value which increases with every data entered by the user. The insert part of the application works fine but when l try to delete a record nothing happens. An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
$records = array();
if(!empty($_POST)) {
if(isset($_POST['firstName'],$_POST['lastName'], $_POST['bio'])){
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$bio = trim($_POST['bio']);
if(!empty($firstName) && !empty($lastName) && !empty($bio)) {
$insert = $db->prepare("INSERT INTO people (firstName, lastName,
bio, created) VALUES (?, ?,?, NOW())");
$insert->bind_param('sss', $firstName, $lastName, $bio);
if($insert->execute()){
header('Location: addressbook.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM people")){
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class = "container">
<?php
if(!count($records)){
echo 'No records found';
}
else{
?>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Bio</th>
<th>Created</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo escape($r->id);?></td>
<td><?php echo escape($r->firstName); ?></td>
<td><?php echo escape($r->lastName); ?></td>
<td><?php echo escape($r->bio); ?></td>
<td><?php echo escape($r->created); ?></td>
<td>
<a onclick="return confirm('Do you want to delete the
record')" href="addressbook.php?idd=<?php echo $row['id'] ?>"
class="btn btn-
danger">Delete</a></td>
<?php
}
?>
</tr>
//My guess is the problem is with this code down here for deleting
<?php
if(isset($_POST['idd'])){
$idd = $_POST['idd'];
$results = $db->query("DELETE FROM people WHERE id=$idd");
if($results){
header('Location: addressbook.php');
}
}
?>
</tbody>
</table>
<?php
}
?>
you need to use $_GET because by default href tag sends the data with GET method.
your code should be
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='$idd'");
if($results){
header('Location: addressbook.php');
}
}
NOTE- use prepared statement for avoiding sql injection attack
`
<?php
//database connectivity
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"<db_name>");
$idd = $_REQUEST['idd'];
$sql= "DELETE FROM people WHERE id='$idd' ";
$result = mysqli_query($con,$sql) or die(mysql_error());
header("refresh:0.1; addressbook.php");
?>`
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='{$idd}'");
Try adding a single quote.
If it still doesn't work, please see if the $_POST is actually posting correctly.
Try $results = $db->query("DELETE * FROM people WHERE id=$idd"); instead of $results = $db->query("DELETE FROM people WHERE id=$idd"); in the delete User Function :)
I have the following code:
$sql = "SELECT * FROM Tickets WHERE stat='Open'";
$result = mysql_query($sql);
mysql_close($con);
?>
<!DOCTYPE>
<html>
<body>
<table class="striped">
<tr class="header">
<td>Username</td>
<td>Title</td>
<td>Description</td>
<td>Admin Name</td>
<td>Category</td>
<td>Status</td>
<td>Urgency</td>
<td>Time In</td>
<td> </td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[username]."</td>";
echo "<td>".$row[title]."</td>";
echo "<td>".$row[description]."</td>";?>
<td><select>
<?php
echo "<option value'".$row[admin_name]."'>".$row[admin_name]."</option>";
$sql = mysql_query("SELECT username FROM Users WHERE user_type='admin'");
while ($u = mysql_fetch_array($sql)){
echo "<option value='".$u['username']."'>".$u['username']."</option>";
}
?>
</select></td>
<?php
echo "<td>".$row[category]."</td>";
echo "<td>".$row[stat]."</td>";
echo "<td>".$row[urgency]."</td>";
echo "<td>".$row[time_in]."</td>";
echo "<td><a href='close.php'>Close Ticket</a></td>";
echo "</tr>";
}
?>
</table>
<a href='update.php'>Update</a>
</body>
</html>
I have two links on this page. Both of them need to update a SQL database. The Close ticket link needs to just update the single row, while the update link should update all of them. I am not sure how to get the info from one php to the next. It seems like you can put the individual row information into a Post array for the close ticket link, but I am not sure how. For the update link it needs to take the value of the dropdown in the table and change the admin_name field to that value.
Hello i got this sample data in sql
$data = array(
array('id' => '1','name' => 'name1','surname' => 'surname1'),
array('id' => '2','name' => 'name2','surname' => 'surname2'),
array('id' => '3','name' => 'name3','surname' => 'surname3'),
array('id' => '4','name' => 'name4','surname' => 'surname4')
);
I want to dispplay in in html table but my code didnt work :
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
}
?>
<tbody>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
</tbody>
</table>
</body>
</html>
But i wann't also that the numer of rows in html table depends by number of columns in sql table. For example in this case i want to display only three rows (three columns in sql table). When i add the column's to sql table i want to rows in html output table increses dynamicly.
Could someone help me with this code ?
Change your code to this:
<tbody>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php
}
?>
</tbody>
You are closing your while loop before displaying the results
You close your while-loop not correct:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<tbody>
<?php while ($data = mysql_fetch_row($result)):?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</body>
</html>
Using the the "while(cond):" and "endwhile;" command you can see better where something starts and where it ends than using the encapsulation with braces.
Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli, since mysql is not anymore actively supported.
You could also use instead:
<?php echo $data['id']?>
rather the shortform:
<?=$data['id']?>
Which is also avaiable w/o php short open after 5.3 (I think it was 5.3)
If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. The following code should do just that and I'm using mysqli which I strongly recommend. The mysql_query extension is deprecated as of PHP 5.5.0.
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to the database ' . $db->connect_error);
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$result = $db->query($select_cols)){
die('There was an error running the query.');
}
while($row = $result->fetch_assoc()){
$cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}
// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);
// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query ' . $db->error);
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<?php foreach ($cols as $k) : // Loop through columns ?>
<th align="center" valign="middle"><?php echo $k; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $k) : // Loop through each $data array() ?>
<tr>
<?php foreach ($k as $v) : // Let's display the records ?>
<td align="center" valign="middle"><?php echo $v; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. If you would like to manually create them simply replace the top php portion with this one:
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$num_cols = $db->query($select_cols)){
die('There was an error running the query.');
}
$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection
// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>
and adjust the html code between <thead></thead>. This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. Please inspect it for any typos as well.
Hope some one can help me out here, i guess am not calling my functions right.
Am trying to retrieve some data from my database and have a delete link attached to each items being retrieved, so that when ever i click on delete, it will delete that particular item which have the delete function.
My Code to retrieve items from database are as follows.
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
And my code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = $_GET['id'];
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
header("Location: vacct.php");
?>
I know am missing out the logic here and hope somebody can direct me or show me the easy way out. at the moment i can successfully retrieve my items from the data base my only problem is to be able to apply the delete function each time the delete button is tapped.
You have to pass the id when you click on the delete link:
<a href=\"delete.php?id=$z[theIdKey]\">
Use the below code.I have added validation and encryption
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = base64_decode($_GET['id']);
if(!empty($id)){
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
}
header("Location: vacct.php");
?>
<td>delete</td>
How are you passing the id to delete to your delete.php script?
Change:
<td>delete</td>
to:
<td>delete</td>
if $z[0] is the ID.
In your delete.php, make sure you also escape the word "transaction" using backtick:
DELETE FROM `transaction` WHERE id=123
this is because "transaction" is a reserved mysql keyword.
Please also read on SQL Injections.