Grading system using php and mysql - php

In the database, some courses value are NULL, and I don't want to print courses that hava a NULL value.
I don't know how I can achieve this in php or mysql. I need something like so:
if(course1!=NULL || course2!=NULL || course3!=NULL || course4!=NULL){
// echo course1; echo course2; echo course3; echo course4; }
The database looks like this:
And the output so far look like this:
A remark() function which check whether the course is A, B, C, D, E, or F is not working properly.
I want the remark() function to output either Excellent, Credit, Pass, or fail base on the grade.
Follows is the code:
function remark(){
global $mathematics, $physics, $chemistry, $lang;
if($mathematics=='A' || $physics=='A' || $chemistry=='A' || $lang=='A'){
$remark = "Excellent";
}
elseif($mathematics=='B' || $physics=='B' || $chemistry=='B' || $lang=='B' || $mathematics=='C' || $physics=='C' || $chemistry=='C' || $lang=='C'){
$remark = "Credit";
}
elseif($mathematics=='D' || $physics=='D' || $chemistry=='D' || $lang=='D' || $mathematics=='E' || $physics=='E' || $chemistry=='E' || $lang=='E'){
$remark = "Pass";
}
else{
$remark = "Fail";
}
return $remark;
}
if(isset($_POST['student_id']) && !empty($_POST['student_id'])){$student_id = $_POST['student_id'];
$check = "SELECT * FROM sample1 WHERE student_id='$student_id'";
$check_query = mysqli_query($connection, $check);
if(mysqli_num_rows($check_query)>0){
while($query_row = mysqli_fetch_assoc($check_query)){
$mathematics = $query_row['mathematics'];
$physics = $query_row['physics'];
$chemistry = $query_row['chm'];
$lang = $query_row['lang'];
echo "<table border=1 width=50%>
<tr> <td>Name: ".$query_row['name']." </td>
<td>Student Id: ".$query_row['student_id']."</td>
<td>Level: ".$query_row['level']."</td>
</tr>
<tr>
<th> Course </th>
<th> Grade </th>
<th> Remark </th>
</tr>
<tr> <td>Mathematics </td> <td>".$mathematics." </td></td> <td>".remark()." </td></tr>
<tr> <td>Physics </td> <td>".$physics."</td> </td><td>".remark()." </td></tr>
<tr> <td>Chemistry </td> <td>".$chemistry."</td> </td><td>".remark()." </td></tr>
<tr> <td>Language </td> <td>".$lang."</td> </td><td>".remark()." </td></tr>
</table>";
}
}
else{echo "Record not found";}
}

About the MYSQL not null values, you use this:
SELECT * FROM yourtable WHERE course1 IS NOT NULL
So, IS NOT NULL will give you queries where that column (course1) is not null. Here more info.
And for PHP, your remark() function has a wrong approach. I will give you one that is correct for your purpouse.
function remark($course){
switch($course) {
case 'A':
return 'Excellent';
break;
case 'B':
case 'C':
return 'Credit';
break;
case 'D':
case 'E':
return 'Pass';
break;
default:
return 'Fail';
break;
}
}
So in your HTML table you do this for each course:
while ($query_row = mysqli_fetch_assoc($check_query)) {
$mathematics = $query_row['mathematics'];
$physics = $query_row['physics'];
$chemistry = $query_row['chm'];
$lang = $query_row['lang'];
echo "<table border=1 width=50%>
<tr> <td>Name: " . $query_row['name'] . " </td>
<td>Student Id: " . $query_row['student_id'] . "</td>
<td>Level: " . $query_row['level'] . "</td>
</tr>
<tr>
<th> Course </th>
<th> Grade </th>
<th> Remark </th>
</tr>"
if(!is_null($mathematics)) echo "<tr> <td>Mathematics </td> <td>" . $mathematics . " </td></td> <td>" . remark($mathematics) . " </td></tr>";
if(!is_null($physics)) echo "<tr> <td>Physics </td> <td>" . $physics . "</td> </td><td>" . remark($physics) . " </td></tr>";
if(!is_null($chemistry)) echo "<tr> <td>Chemistry </td> <td>" . $chemistry . "</td> </td><td>" . remark($chemistry) . " </td></tr>";
if(!is_null($lang)) echo "<tr> <td>Language </td> <td>" . $lang . "</td> </td><td>" . remark($lang) . " </td></tr>";
echo "</table>";
}

Quick answer for the first issue extending the answer of #P0IT10n (?):
<?php
if(!is_null($mathematics)) {
?>
<tr> <td>Mathematics </td> <td>".$mathematics." </td></td> <td>".remark($mathematics)." </td></tr>
<?php
}
?>
// repeat for other courses
BUT
rethink your database structure.
Once you have another course you're f***...
Courses should have their own table, results another one.
Read about database normalisation!
EDIT
Another extension:
It would be even easier if you'd have an array like this:
$remarks = array('A'=>'Excellent', 'B'=>'Good',...);
then you need no extra function with a switch, all you need to do is:
echo $remarks[$mathematics]; // -> Excellent

Related

Displaying MySQL in PHP

So far, I have this program that links my phpmyadmin database to my php script. Now, I need to display certain things in a table like "all records," "all contacts whose last name starts with S," "all pet owners," etc. My question is: is there a simpler way to insert code into my php script to display the information from my database. Right now I have that long echo statement to display the information. Is there a way I can just use something like a SELECT * statement to display all records and to simplify my code?
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli( $db_hostname,
$db_username,
$db_password,
$db_database);
if ($connection->connect_error) {
echo "Sorry";
} else {
echo "Connected!<br><br>";
$sql = "SELECT * FROM People";
$result = $connection->query($sql);
if (!$result) die ($connection->error);
$n = $result->num_rows;
for ($i=1; $i<=$n; $i++) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<table>
<tr><th>ID</th><th>First Name</th><th>Last Name</th>
<th>Street Address</th><th>City</th>
<th>State</th><th>Zip Code</th>
<th>Email Address</th><th>Comment</th>
<th>Number of pets</th></tr>";
echo "<tr><td width=20>" . $row['iD'] . "</td><td>" . $row['First Name'] . "</td><td width=40>" .
$row['Last Name'] . "</td><td width=200>" . $row['Street Address'] . "</td><td width=30>" .
$row['City'] . "</td><td width=40>" . $row['State'] . "</td><td width=30>" .
$row['Zip Code'] . "</td><td width=40>" . $row['Email Address'] . "</td><td width=20>" .
$row['Comment'] . "</td><td width=10>" . $row['Number of pets'] . "</td></tr>";
}
echo "</table>";
}
?>
You should a table structure first then insert your PHP codes within the structure. E.g:
<?php
// Put your MYSQLI retrievals codes here
?>
<table>
<tr>
<th>FIELD_1</th>
<th>FIELD_2</th>
<th>FIELD_3</th>
</tr>
<?php
while ($rows = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><?php echo $rows['field_1']; ?></td>
<td><?php echo $rows['field_2']; ?></td>
<td><?php echo $rows['field_3']; ?></td>
</tr>
<?php
}
?>
</table>
Technically you are doing everything alright, but there are some more sophisticated ways to develop the things you want.
Take a look at the following links:Object oriented programming in PHP and templating in PHP.
Hope this works for you:
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
echo "Connected!<br><br>";
}
$last_name = "Lastname to search"; //You can post or get lastname in here.
/* create a prepared statement */
if ($sql = $connection->prepare("SELECT * FROM People WHERE `Last Name`=?")) {
/* bind parameters for markers */
$sql->bind_param("s", $last_name);
/* execute query */
$sql->execute();
/* instead of bind_result: */
$result = $sql->get_result();
/* close statement */
$sql->close();
}
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Street Address</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Email Address</th>
<th>Comment</th>
<th>Number of pets</th>
</tr>
</thead>
<tbody>
<?
/* now you can fetch the results into an array */
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td width=20><?=$row['iD'];?></td>
<td><?=$row['First Name'];?></td>
<td width=40><?=$row['First Name'];?></td>
<td width=200><?=$row['Street Address'];?></td>
<td width=30><?=$row['City'];?></td>
<td width=40><?=$row['State'];?></td>
<td width=30><?=$row['Zip Code'];?></td>
<td width=40><?=$row['Email Address'];?></td>
<td width=20><?=$row['Comment'];?></td>
<td width=10><?=$row['Number of pets'];?></td>
</tr>
<?
}
?>
</tbody>
</table>

How to make a PHP variable loop in template

I am trying to make something so it shows the database results. The problem is, it only shows 1 result. I want it to show multiple results using an quick and dirty template system. Also, is there a way to make my system better? Perhaps a class or a function? I need some insight on this. Thanks a bunch!
cp.php
<?php
require("db.php");
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
$title = "********";
require("templates/header.php");
if($mybb->user['uid'])
{
$uid = $mybb->user['uid'];
// Active Tournaments
// run queries, do all the brainwork
// lets get the forum name
$query = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$uid}";
$result = mysqli_query($conn, $query);
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$activetournaments = "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td>";
// $team = mysqli_query($conn, "SELECT * FROM tourneys WHERE id=" . $row['tid'] . "");
// $playing = mysqli_query($conn, "SELECT `` FROM tourneys WHERE id=" . $row['tid'] . "");
}
}
else
{
$error = "Only registered members may access this area.";
include ('templates/error.php');
}
require ("templates/cp.php")
?>
templates/cp.php
<h2>Welcome back <?=$mybb->user['username']; ?>!</h2>
<?=$postrequirement?>
<h3>Active Tournaments</h3>
<table>
<tr>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Playing as</th>
<th>Options</th>
</tr>
<tr>
<?=$activetournaments?>
</table>
<hr />
<h3>Participated Tournaments</h3>
<table>
<tr>
<th>Position</th>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Played as</th>
<th>Options</th>
</tr>
<tr>
<?=$participatedtournaments?>
</table>
I have changed $activetournaments to append to the end using '.='.
while($row = mysqli_fetch_assoc($result)) {
$activetournaments .= "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td> ";
}
At the moment, for each record, it is overwriting $activetournaments. You could also use $activetournaments as an array then do a while / foreach in the template.
In your cp.php you overwrite $activetournaments in each while execution, change your code to:
<?php
require("db.php");
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
$title = "1ShotGG Tournaments | Control Panel";
require("templates/header.php");
if($mybb->user['uid'])
{
$uid = $mybb->user['uid'];
// Active Tournaments
// run queries, do all the brainwork
// lets get the forum name
$query = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$uid}";
$result = mysqli_query($conn, $query);
// output data of each row
$activetournaments = '';
while($row = mysqli_fetch_assoc($result)) {
$activetournaments .= "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td>";
// $team = mysqli_query($conn, "SELECT * FROM tourneys WHERE id=" . $row['tid'] . "");
// $playing = mysqli_query($conn, "SELECT `` FROM tourneys WHERE id=" . $row['tid'] . "");
}
}
else
{
$error = "Only registered members may access this area.";
include ('templates/error.php');
}
require ("templates/cp.php")
?>
In your templates/cp.php you can add a </tr> tag here:
<tr>
<?=$activetournaments?>
</tr>
your new templates/cp.php:
<h2>Welcome back <?=$mybb->user['username']; ?>!</h2>
<?=$postrequirement?>
<h3>Active Tournaments</h3>
<table>
<tr>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Playing as</th>
<th>Options</th>
</tr>
<tr>
<?=$activetournaments?>
</tr>
</table>
<hr />
<h3>Participated Tournaments</h3>
<table>
<tr>
<th>Position</th>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Played as</th>
<th>Options</th>
</tr>
<tr>
<?=$participatedtournaments?>
</table>

If statement inside a print - PHP

I need to do a if statement inside a print, i have this
while($data=$results->fetchrow()) {
$id = $data['id'];
$stuff = $data['stuff'];
print ('
<tr>
<td>'.$id.'</td>'
if ($stuff == 1){
print "<td>".$age."<td><td> </td> ";
}else{
print "<td> </td><td> ".$age."</td>";
}'
<td>bla bla</td>
<td>bla bla</td>
</tr>
');
and this is not working for me, so please guys, help me! :)
Try this, I just moved it outside the print statement.
<?php
while($data=$results->fetchrow()) {
$id = $data['id'];
$stuff = $data['stuff'];
if ($stuff == 1){
$foo = "<td>".$age."<td><td> </td> ";
}else{
$foo = "<td> </td><td> ".$age."</td>";
}
print ('
<tr>
<td>'.$id.'</td>'
.$foo.
'<td>bla bla</td>
<td>bla bla</td>
');
You can use a conditional, aka ternary, expression:
print ('
<tr>
<td>'.$id.'</td>'.
($stuff == 1 ?
"<td>".$age."<td><td> </td> " :
"<td> </td><td> ".$age."</td>") .
'
<td>bla bla</td>
<td>bla bla</td>
');

Ajax responsetext as a table output?

I'm not really familiar with Ajax Response - I have edited the PHP Ajax Search code from W3schools.com as follows :
<?php
require_once('connect_db.php');
$query = "select item_no from items";
$result = mysql_query($query);
$a = array();
while ($row = mysql_fetch_assoc($result)){
$a[] = $row['item_no'];
}
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="No Suggestion";
}
else
{
$response=$hint;
}
//output the response
echo "<table border=1><tr><td>".$response."</td></tr></table>";
?>
The output of the above code works perfectly, but they are all listed like this (2L500BU , 2L500GO , 2L500NA , 2L500RD , 2L802CA , 2L802WH , 2L803GR , 2L804BE , 2L804BK , 2L804CO , 2L805BU , 2L806BE , 2L806GR ) - Those numbers are Item No in mysql table called items.
Now :
1) I want to output the response into table with <tr> for each like this
2l500BU
2L500GO
.
.
.
.
etc.
2) Do you think its possible to output all table records from Mysql based on the hint entered as follows :
$sql="SELECT * FROM items WHERE item_no = '".**$hint**."'";
$result = mysql_query($sql);
echo "<table align='center' cellpadding='3' cellspacing='3' width='800px' border='1' font style='font-family:arial;'>";
echo "
<tr align=center>
<th style=font-size:18px; bgcolor=#20c500>Item Number</th>
<th style=font-size:18px; bgcolor=#20c500>QTY</th>
<th style=font-size:18px; bgcolor=#20c500>Actual Price</th>
<th style=font-size:18px; bgcolor=#20c500>Selling Price</th>
<th style=font-size:18px; bgcolor=#20c500>Difference</th>
<th style=font-size:18px; bgcolor=#20c500>Date</th>
</tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr align=center bgcolor=#e3e3e3>";
echo "<td style='font-size:18px; font-weight:bold;'>" . strtoupper($row['item_no']) . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['qty'] . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['actual_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['discount_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['difference_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . date("d-m-Y",strtotime($row['date'])) . "</td>";
echo "</tr>";
}
echo "<table>";
If you're wanting to fetch items from a database and display a row for each of them, this is how you'd do it with jQuery.
Your PHP script:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$sql = "SELECT item_no FROM items";
$res = $mysqli->query($sql);
while ($row = $res->fetch_assoc()) {
$rows[] = $row['item_no'];
}
header('Content-Type: application/json');
echo json_encode($rows);
?>
And your HTML with the table:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<thead>
<tr>
<th scope="col">Item No.</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script src="js/lib/jquery.js"></script>
<script>
$(document).ready(function() {
$.getJSON('yourscript.php', function(items) {
$.each(items, function(i, item) {
$('tbody').append('<tr><td>' + item + '</td></tr>);
});
});
});
</script>
I've also used MySQLi (MySQL improved) rather than the standard mysql_ functions, as the mysql_ library is deprecated and you should be using either MySQLi or PDO now.

how to give color to table tr?

Hello i have a table with some fields like
here i want make colors for table entire rows..means if ASR value is 75 to 100 should get one color and 50 to 75 should get another color and below 50 should get another color.
and here is my php code
<table width="75%" border="1">
<tr>
<td align="center">channel no</td>
<td align="center">IP</td>
<td align="center">Total calls</td>
<td align="center">Connected calls</td>
<td align="center">Disconnected calls</td>
<td align="center">Duration</td>
<td align="center">ASR</td>
<td align="center">ACD</td>
</tr>
<?php
while ($row = mysql_fetch_assoc($result)) {
//$minutes = gmdate("H:i:s", $row['tduration']);
echo "<tr>
<td>".$row['channel']." </td>
<td>".$row['ip']." </td>
<td>".$row['totalcalls']." </td>";
if ($row['totalcalls']>1){
$sql1 = "SELECT count(duration) as count FROM gateways where duration=0 and ip='".$_POST['ip']."' and channel='".$row['channel']. "' and (connect_datetime BETWEEN ' ".$_POST['toval']." ' and '".$_POST['fromval']."' or disconnect_datetime BETWEEN ' ".$_POST['toval']." ' and '".$_POST['fromval']."' ) Group by channel";
$result1 = mysql_query($sql1, $link);
$norow=mysql_fetch_assoc($result1);
$attenedcalls=($row['totalcalls']-$norow['count']);
echo "<td>".$attenedcalls." </td>";
$disconnectedcalls=($row['totalcalls']-$attenedcalls);
echo "<td>".$disconnectedcalls." </td>";
echo " <td>".$row['tduration']." </td>";
echo "<td>".(($attenedcalls/$row['totalcalls'])*100)."</td>";
}else{
echo "<td>".$row['totalcalls']."</td>";
echo "<td>100</td>";
}
$minutes = gmdate("H:i:s", ($row['tduration']/$attenedcalls));
echo " <td>".$minutes." </td>
</tr>";
}
?>
</table>
thanks in advance
You can try like this
<table width="75%" border="1">
<tr>
<td align="center">channel no</td>
<td align="center">IP</td>
<td align="center">Total calls</td>
<td align="center">Connected calls</td>
<td align="center">Disconnected calls</td>
<td align="center">Duration</td>
<td align="center">ASR</td>
<td align="center">ACD</td>
</tr>
<?php
while ($row = mysql_fetch_assoc($result)) {
$color = '';
if ($row['totalcalls']>1){
$sql1 = "SELECT count(duration) as count FROM gateways where duration=0 and ip='".$_POST['ip']."' and channel='".$row['channel']. "' and (connect_datetime BETWEEN ' ".$_POST['toval']." ' and '".$_POST['fromval']."' or disconnect_datetime BETWEEN ' ".$_POST['toval']." ' and '".$_POST['fromval']."' ) Group by channel";
$result1 = mysql_query($sql1, $link);
$norow=mysql_fetch_assoc($result1);
$attenedcalls=($row['totalcalls']-$norow['count']);
$asr = (($attenedcalls/$row['totalcalls'])*100);
if($asr >= 75 && $asr <=100 ){
$color = 'red';
}else if($asr >= 50 && $asr < 75){
$color = 'cyan';
}else if($asr < 50){
$color = 'blue';
}
}
//$minutes = gmdate("H:i:s", $row['tduration']);
echo "<tr style='background-color : ".$color."'>
<td>".$row['channel']." </td>
<td>".$row['ip']." </td>
<td>".$row['totalcalls']." </td>";
if ($row['totalcalls']>1){
echo "<td>".$attenedcalls." </td>";
$disconnectedcalls=($row['totalcalls']-$attenedcalls);
echo "<td>".$disconnectedcalls." </td>";
echo " <td>".$row['tduration']." </td>";
echo "<td>".$asr."</td>";
}else{
echo "<td>".$row['totalcalls']."</td>";
echo "<td>100</td>";
}
$minutes = gmdate("H:i:s", ($row['tduration']/$attenedcalls));
echo " <td>".$minutes." </td>
</tr>";
}
?>
</table>
[...]
while ($row = mysql_fetch_assoc($result)) {
$asrVal=(($attenedcalls/$row['totalcalls'])*100);
if($asrVal>=50 && $asrVal <=75) $class="from50to75";
if($asrVal>=75 && $asrVal <=100) $class="from75to100";
if($asrVal<50) $class="below50";
//$minutes = gmdate("H:i:s", $row['tduration']);
echo "<tr class='$class'>
[...]
then add:
<style>
tr.from50to75 td{background-color:red;}
tr.from75to100 td{background-color:green;}
tr.below50 td{background-color:blue;}
</style>
Modify your while loop so that you compute the ASR value before emitting the <tr> tag. Use that value to select a class according to the classification you have set up, and emit a tag of the form <tr class=foo> where foo is the class name you have selected. Then it’s just a matter of writing CSS rules for the classes, using class selectors like tr.foo.
(Provided that you have not set color on the td cells. If you have, you need to use selectors like tr.foo td to override such settings.)

Categories