I have this Function:
function getLow() {
global $db_prefix, $min;
//get latest week with all entered scores
$lastCompletedWeek = getLastCompletedWeek();
$sql = "select u.userID, u.teamName ";
$sql .= "from " . $db_prefix . "users u ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
for($i = 1; $i <= $lastCompletedWeek; $i++) {
$userScore = getLowScore($i, $result['userID']);
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
}
$count = count($win);
$lowest = 0;
$min[score] = PHP_INT_MAX;
$min[user] = $result['userID'];
$min[teamName] = $result['teamName'];
for($i = 0; $i < $count; $i++) {
if($win[$i + 1]['user'] == $result['userID']) {
if($win[$i + 3]['score'] < $min[score]) {
$min[score] = $win[$i + 3]['score'];
$lowest = $i;
}
}
}
unset($win[$lowest]);
unset($win[$lowest + 1]);
unset($win[$lowest + 2]);
unset($win[$lowest + 3]);
$win = array_values($win);
//print_r ($min);
//echo $min[teamName] . ' ' . $min[score] . ' ';
}
}
when I call it from another .php file like this:
getLow($min);
I only get the last record....why?
Here is the getLowScores functio as well.
function getLowScore($week, $userID) {
global $db_prefix, $user;
$score = 0;
//get array of games
$games = array();
$sql = "select * from " . $db_prefix . "schedule where weekNum = " . $week . " order by gameTimeEastern, gameID";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$games[$result['gameID']]['gameID'] = $result['gameID'];
$games[$result['gameID']]['homeID'] = $result['homeID'];
$games[$result['gameID']]['visitorID'] = $result['visitorID'];
$games[$result['gameID']]['tie'] = 1;
if (($result['homeScore'] + (($result['visitorSpread'] * -1))) > ($result['visitorScore'] + (($result['homeSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['homeID'];
}
if (($result['visitorScore'] + (($result['homeSpread'] * -1))) > ($result['homeScore'] + (($result['visitorSpread'] * -1)))) {
$games[$result['gameID']]['winnerID'] = $result['visitorID'];
}
if (($result['visitorScore'] + ($result['homeSpread'] * -1)) == ($result['homeScore'] + ($result['visitorSpread'] * -1))) {
$games[$result['gameID']]['winnerID'] = $result['tie'];
}
}
//loop through player picks & calculate score
$sql = "select p.userID, p.gameID, p.pickID, p.points, u.paid ";
$sql .= "from " . $db_prefix . "picks p ";
$sql .= "inner join " . $db_prefix . "users u on p.userID = u.userID ";
$sql .= "inner join " . $db_prefix . "schedule s on p.gameID = s.gameID ";
$sql .= "where s.weekNum = " . $week . " and u.userID = " . $userID . " ";
$sql .= "order by u.lastname, u.firstname, s.gameTimeEastern";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
if (!empty($games[$result['gameID']]['winnerID']) && $result['pickID'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
if ($result['tie'] == $games[$result['gameID']]['winnerID']) {
//player has picked the winning team
$score++;
}
}
return $score;
}
Thanks in advance for helping!! This is driving me crazy?
Maybe not the answer, but this code is very broken:
$win[][week] = $i;
$win[][user] = $result['userID'];
$win[][teamName] = $result['teamName'];
$win[][score] = $userScore;
First, that adds four new rows to $win, a new one every time you use the [], which I very much doubt is your intent.
Second, those should be quoted, so it is ["week"], not [week]. Turn on PHP warnings and follow them.
I think you want:
$win[] = array(
"week" => $i,
"user" => $result['userID'],
"teamName" => $result['teamName'],
"score" => $userScore,
);
You can make warnings appear with:
error_reporting(E_ALL);
ini_set("display_errors",1);
Related
How to show the total bonus in red color at the screenshot below ?
Demo link : http://client.bfm.expert/test_unilevel1.php
Code :
<?php
//Use the following function to get the data of downlines
function getChildren($parent) {
//list out members by rank
$query = "SELECT user_id, first_name, sponsor_id, rank FROM tbl_user_master WHERE sponsor_id = $parent";
$result = $conn->query($query);
$children = array();
$i = 0;
$result = $conn->query($query) or die($conn->error);
while($row = $result->fetch_assoc())
{
$children[$i] = array();
$children[$i]['userid'] = $row['user_id'];
$children[$i]['name'] = $row['first_name'];
$children[$i]['rank'] = $row['rank'];
$children[$i]['children'] = getChildren($row['user_id']);
$i++;
}
return $children;
}
//modify rank = 4 to 2 to calculate unilevel bonus for rank IAM
$query2 = "SELECT user_id, first_name FROM tbl_user_master WHERE rank = 3";
$result2 = $conn2->query($query2);
$result2 = $conn2->query($query2) or die($conn2->error);
while($row2 = $result2->fetch_assoc())
{
$member_id = $row2['user_id'];
$member_name = $row2['first_name'];
$finalResult = getChildren($member_id); //enter sponsor_id here
echo "Unilevel Bonus for user id : " . $member_id . " " . $member_name . " - Total Unilevel Bonus for lvl1 : Usd??? , lvl2 : Usd???, lvl3 : Usd??? <br /> ";
printList($finalResult);
}
//display all downlines of the sponsor
function printList($array = null, $level = 1) {
$m_profit = 168000;
$Total_investment = 1500000;
$unibonus_percent = 0.00;
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo $item['name'];
echo " - Rank : " . $item['rank'];
echo " - level : " . $level;
//show unilevel bonus
$unibonus_percent = 0.06;
//show how many package_lot
$userid = $item['userid'];
$query3 = "SELECT user_id, package_id, package_amount FROM tbl_product_order WHERE user_id = $userid && status=3";
$result3 = $conn3->query($query3);
$result3 = $conn3->query($query3) or die($conn3->error);
while($row3 = $result3->fetch_assoc()) {
$package_siz = $row3['package_amount'] / 1500;
echo " - LOT : " . $package_siz;
$unibonus = (($m_profit / ($Total_investment / 1500)) * $unibonus_percent) * $package_siz;
echo " - unibonus : USD" . $unibonus;
}
if (count($item['children'])) {
printList($item['children'], $level+1);
}
echo "</li>";
}
echo "</ul>";
}
}
?>
Use call by refrence for total bonus calculation
here is an example
$Bonus = 0;
printList($array = null, 1, $Bonus);
echo $Bonus;
function printList($array = null, $level = 1, &$Bonus = 0) {<---call by referance for bonus
if ($level == 10) {
return; //only for break recursive
}
$Bonus = $Bonus + $level;
printList($array = null, $level + 1, $Bonus);
}
I have this class that has these two methods that are so closely related to the each other. I do not want to pass the flags so I kept them separate. I was wondering if there is a way to rewrite it so that I do not have to repeat so closely!
class Test extends Controller
{
public static function nonFormattedData($param)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
foreach ($rs as $row) {
$records = new Account();
$results[] = $records;
}
return $results;
}
}
public static function formattedData($serArray, $orderBy = "giftcardaccount_id desc", $offset = 0, $limit = 10)
{
$arr = array();
if (is_array($param)) {
$i = 0;
$sql = "
select *
from table1
where
";
if (isset($param['startDate'])) {
$sql .= " date_created between ? AND ?";
$arr[] = $param['startDate'];
$arr[] = $param['endDate'];
$i++;
}
if (isset($param['amount']) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param) && !empty($param['amount'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " balance= ?";
$arr[] = $param['amount'];
$i++;
}
if (isset($param['createdBy']) && !empty($param['createdBy'])) {
if ($i > 0) $sql .= " AND ";
$sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'";
}
$sql .= ' group by id.table1 ';
$rs = Query::RunQuery($sql, $arr);
return array("data" => $rs);
}
}
}
Why not have one method, but with an optional formatting options object/array?
public static function getData($params, $formatting = null) {
// continue as normal, adding formatting if it's there
}
I am trying to use K2 Tool's tag cloud function on my joomla website but the only setting I can pick is by X Popular Tags which doesn't actually specific what makes the tag popular.
So I am trying to make it so that the tag cloud works as X Random instead. So everytime the page/module is reloaded, X say 20 would display 20 randomly chosen tags.
I look through the module's code and found the function in helper.php but I don't understand how the code select the tags. My guess is if I want to change it to use X random instead of X popular, I would need to change the query for $query?
function tagCloud(&$params) {
$mainframe = &JFactory::getApplication();
$user = &JFactory::getUser();
$aid = (int) $user->get('aid');
$db = &JFactory::getDBO();
$jnow = &JFactory::getDate();
$now = $jnow->toMySQL();
$nullDate = $db->getNullDate();
$query = "SELECT i.id FROM #__k2_items as i";
$query .= " LEFT JOIN #__k2_categories c ON c.id = i.catid";
$query .= " WHERE i.published=1 ";
$query .= " AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." ) ";
$query .= " AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )";
$query .= " AND i.trash=0 ";
if(K2_JVERSION=='16'){
$query .= " AND i.access IN(".implode(',', $user->authorisedLevels()).") ";
}
else {
$query .= " AND i.access <= {$aid} ";
}
$query .= " AND c.published=1 ";
$query .= " AND c.trash=0 ";
if(K2_JVERSION=='16'){
$query .= " AND c.access IN(".implode(',', $user->authorisedLevels()).") ";
}
else {
$query .= " AND c.access <= {$aid} ";
}
$cloudCategory = $params->get('cloud_category');
if(is_array($cloudCategory)) {
$cloudCategory = array_filter($cloudCategory);
}
if ($cloudCategory) {
if(!is_array($cloudCategory)){
$cloudCategory = (array)$cloudCategory;
}
foreach($cloudCategory as $cloudCategoryID){
$categories[] = $cloudCategoryID;
if($params->get('cloud_category_recursive')){
$children = modK2ToolsHelper::getCategoryChildren($cloudCategoryID);
$categories = #array_merge($categories, $children);
}
}
$categories = #array_unique($categories);
JArrayHelper::toInteger($categories);
if(count($categories)==1){
$query .= " AND i.catid={$categories[0]}";
}
else {
$query .= " AND i.catid IN(".implode(',', $categories).")";
}
}
if(K2_JVERSION == '16') {
if($mainframe->getLanguageFilter()) {
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND c.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") ";
}
}
$db->setQuery($query);
$IDs = $db->loadResultArray();
$query = "SELECT tag.name, tag.id
FROM #__k2_tags as tag
LEFT JOIN #__k2_tags_xref AS xref ON xref.tagID = tag.id
WHERE xref.itemID IN (".implode(',', $IDs).")
AND tag.published = 1";
$db->setQuery($query);
$rows = $db->loadObjectList();
$cloud = array();
if (count($rows)) {
foreach ($rows as $tag) {
if (#array_key_exists($tag->name, $cloud)) {
$cloud[$tag->name]++;
} else {
$cloud[$tag->name] = 1;
}
}
$max_size = $params->get('max_size');
$min_size = $params->get('min_size');
$max_qty = max(array_values($cloud));
$min_qty = min(array_values($cloud));
$spread = $max_qty - $min_qty;
if (0 == $spread) {
$spread = 1;
}
$step = ($max_size - $min_size) / ($spread);
$counter = 0;
arsort($cloud, SORT_NUMERIC);
$cloud = #array_slice($cloud, 0, $params->get('cloud_limit'), true);
uksort($cloud, "strnatcasecmp");
foreach ($cloud as $key=>$value) {
$size = $min_size + (($value - $min_qty) * $step);
$size = ceil($size);
$tags[$counter]-> {'tag'} = $key;
$tags[$counter]-> {'count'} = $value;
$tags[$counter]-> {'size'} = $size;
$tags[$counter]-> {'link'} = urldecode(JRoute::_(K2HelperRoute::getTagRoute($key)));
$counter++;
}
return $tags;
}
}
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners`
WHERE `scanners.Date` = '" . $date . "'
AND `scanners.Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `ArchiveBundle.KordNo` = '" . $x['scanners.KordNo'] . "'
AND `ArchiveBundle.BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
I have edited the class above which pulls no results. However the original class below pulls results out. Please can someone help.
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `KordNo`, `BundleNumber`
FROM `scanners`
WHERE `Date` = '" . $date . "'
AND `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['KordNo'] . "'
AND `BundleNumber` = '" . $x['BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
The class above counts the amount of shoes produced. I have had to edit this class so it can exclude certain types of shoes but it does not seem to pull any results for some reason.
UPDATE.
This is the class scanners. This is what its currently at the moment. I'm fairly new to php and this code was writted by my predecessor.
<?php
class CHScanners {
var $conn;
// Constructor, connect to the database
public function __construct() {
require_once "/var/www/reporting/settings.php";
define("DAY", 86400);
if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error());
if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error());
}
public function ListRoomBundles($room, $date, $dateTo = null) {
// If dateTo hasn't been set, make it now
if(!isset($dateTo) or $dateTo == "") {
$dateTo = $date;
}
// Return an array with each bundle number and the quantity for each day
$scanner = $this->GetScannerNumber($room);
$sql = "SELECT * FROM `scanners` WHERE `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0)
AND `Date` BETWEEN '" . $date . "' AND '" . $dateTo . "'
GROUP BY `KordNo`, `BundleNumber`;";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$sql = "SELECT `BundleReference`, `QtyIssued`, `WorksOrder`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $row['KordNo'] . "'
AND `BundleNumber` = '" . $row['BundleNumber'] . "';";
$result2 = mysql_query($sql);
while($row = mysql_fetch_array($result2)) {
if($row[0] != "") {
$final[] = $row;
} else {
$final[] = array("Can't find bundle number", "N/A");
}
}
}
return $final;
}
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners,TWOrder,Stock`
INNER JOIN TWORDER ON `scanners.KordNo` = `TWOrder.KOrdNo`
AND `scanners.Date` = '" . $date . "'
INNER JOIN Stock ON `TWOrder.Product` = `Stock.ProductCode`
AND `Stock.ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners.Scanner` IN (
ORDER BY `scanners.KordNo' ASC";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['scanners.KordNo'] . "'
AND `BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
// We need a function to select the previous Monday from a given date
public function GetPreviousMonday($timestamp) {
if(date("N", $timestamp) == 1) {
return $timestamp;
} elseif(in_array(date("N", $timestamp), array(2, 3, 4, 5))) {
return $timestamp - (date("N", $timestamp)-1)*DAY;
} elseif(in_array(date("N", $timestamp), array(6, 7))) {
return $timestamp + (date("N", $timestamp)*(-1)+8)*DAY;
} else {
return false;
}
}
public function GetRoomName($room) {
// Return the room name from the room number
switch($room) {
case 1:
return "Skin Room";
case 2:
return "Clicking Room";
case 3:
return "Kettering";
case 4:
return "Closing Room";
case 5:
return "Rushden";
case 6:
return "Assembly Room";
case 7:
return "Lasting Room";
case 8:
return "Making Room";
case 9:
return "Finishing Room";
case 10:
return "Shoe Room";
}
}
public function GetDueDateForWorksOrder($worksOrderNumber) {
$sql = "SELECT `DueDate`
FROM `TWOrder`
WHERE `WorksOrderNumber` = '" . $worksOrderNumber . "';";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
$result = mysql_query($sql, $this->conn);
$row = mysql_fetch_row($result);
return $row[0];
}
private function GetScannerNumber($room) {
// Get the room number from the scanner number
switch($room) {
case 1:
$scanner = array(3);
break;
case 2:
$scanner = array(10,11,15);
break;
case 3:
$scanner = array(5);
break;
case 4:
$scanner = array(5);
break;
case 5:
$scanner = array(5);
break;
case 6:
$scanner = array(6);
break;
case 7:
$scanner = array(9);
break;
case 8:
$scanner = array(8);
break;
case 9:
$scanner = array(12);
break;
case 10:
$scanner = array(14);
break;
default:
$scanner = array(0);
break;
}
return $scanner;
}
}
?>
You have a typo - a letter is missing in the last line of this block of code:
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] .
Here the array item should be $x['scanners.BundleNumber'].
I have an attendance page which outputs a list of students in a class through the following loop:
$sql10 = "SELECT class.name, student_to_class.class_id, student_to_class.student_id
FROM
student_to_class
INNER JOIN
class
ON class.id=student_to_class.class_id
WHERE
class.name = '$classid'";
$result10 = mysql_query($sql10) or die(mysql_error());
while ($row = mysql_fetch_array($result10)) {
$student = $row['student_id'];
$classid = $row['class_id'];
$sql3 = "select * from student where id = '$student'";
$result3 = mysql_query($sql3) or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$studentfname = $row3['first_name'];
$studentlname = $row3['last_name'];
$sql4 = "select * from student where first_name = '$studentfname' AND last_name = '$studentlname'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
$studentrfid = $row4['rfid'];
$sql5 = "select * from class where id = '$classid'";
$result5 = mysql_query($sql5) or die(mysql_error());
$row5 = mysql_fetch_assoc($result5);
$class_name = $row5['name'];
//Define the default variables assuming attendance hasn't been taken.
$david = "select * from student where rfid='$studentrfid'";
$davidresult = mysql_query($david) or die(mysql_error());
$drow = mysql_fetch_assoc($davidresult);
if (($drow['excused'] == '1') && ($drow['excuseddate'] == $date)) {
//if($drow['excuseddate'] == $date;
$excusedabsense = '<option value="Excused Absense" label="Excused Absense" selected="selected">Excused Absense</option>';
} else {
$excusedabsense = '';
}
$presentpunctual = '<option value="Present" label="Present">Present</option>';
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
if (isset($_POST['editdate'])) {
$date = $_POST['date'];
}
$realfname = $studentfname;
$reallname = $studentlname;
$sql4 = "select * from attendance_main where StudentID = '$studentrfid' AND date = '$date' AND classID = '$class_name'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
if ($row4['status'] == "Present") {
$presentpunctual = '<option value="Present" label="Present" selected="selected">Present</option>';
} else {
$presentpunctual = '<option value="Present" label="Present">Present</option>';
}
if ($row4['status'] == "Tardy") {
$presenttardy = '<option value="Tardy" label="Tardy" selected="selected">Tardy</option>';
} else {
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
}
if ($row4['status'] == "Absent") {
$unexcusedabsense = '<option value="Absent" label="Absent" selected="selected">Absent</option>';
} else {
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
}
$b++;
echo "<tr>";
if (!isset($dateform)) {
$dateform = date('m/d/Y');
}
$date = date('m/d/Y');
echo '<td><iframe src="flag.php?&flagdate=' . $dateform . '&curdate=' . $date . '&class=' . $classid . '&flag=1&user=' . $studentrfid . '&curflag=' . $realrfid['flag'] . '&flagclass=' . $classname . '" width="50" height="30" frameborder="0" scrolling="no"> </iframe></td>';
//Yesterday
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$yesterdaysql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_yesterday = "N/A";
} else {
$tooltipresult_yesterday = $tooltiprow['status'];
}
//2 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days2sql' AND classID = '$classid'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_2days = "N/A";
} else {
$tooltipresult_2days = $tooltiprow['status'];
}
//3 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days3sql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_3days = "N/A";
} else {
$tooltipresult_3days = $tooltiprow['status'];
}
$tooltip = "<b>" . $yesterday . ":</b> " . $tooltipresult_yesterday . " - <b>" . $days2 . ":</b> " . $tooltipresult_2days . " - <b>" . $days3 . ":</b> " . $tooltipresult_3days;
echo "
<!-- Loop #" . $b . " --> <td><a href='#'";
?> onMouseover="ddrivetip('<?php
echo $tooltip;
?>')"; onMouseout="hideddrivetip()"> <?php
echo $realfname . " " . $reallname . "</a></td>";
echo '<td>
<select name="status' . $b . '">
' . $presentpunctual . '
' . $presenttardy . '
' . $excusedabsense . '
' . $unexcusedabsense . '
</select>
' . $hiddenfield . '
<input type="hidden" name="i" value="' . $b . '" />
<input type="hidden" name="studentid' . $b . '" value="' . $studentrfid . '">
<input type="hidden" name="classid" value="' . $class_name . '"></td>
<td><input type="text" name="comments' . $b . '" size="40" /></td></tr>
<!-- End Loop -->';
}
}
}
It essentially prints out student name and a drop down of statuses (if attendance was taken that day, the status will be whatever is set in the database). The date, flag, and tooltip functions are extra additions. (Date is for previous days, tooltip shows previous attendance on hover)
This data is being executed through the following loop:
if (isset($_GET['update'])) {
mysql_query("UPDATE teacher_accounts SET attendance = '1' WHERE username = '$username'") or die(mysql_error());
$error = 0;
$limit = $_GET['i'];
$starter = 0;
$num = 0;
while ($starter < $limit) {
$num++;
$statusinc = "status" . $num;
$studentinc = "studentid" . $num;
$commentsinc = "comments" . $num;
$starter++;
$studentID = $_GET[$studentinc];
$status = $_GET[$statusinc];
$comments = $_GET[$commentsinc];
$date = date("m/d/Y");
$sql = "select * from student where id = '$studentID'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$classid = $_GET['classid'];
if (isset($_GET['dateedit'])) {
$date = $_GET['dateedit'];
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
}
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance.</h3>";
}
} else {
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance for " . $num . " students.</h3>";
}
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
if (mysql_query($sql)) {
$return = "<h3>Successfully inserted today's attendance for " . $num . " students.";
}
}
}
}
echo $return;
For some reason, data is sometimes not being inserted properly. For example, a teacher might submit attendance on 02/08/2011, for a specific class, and certain students might appear twice under that attendance. This shouldn't be the case according to the code, because it should first check if they exist and, if they do, update the record rather than insert.
I've also seen cases where records are randomly deleted altogether. When a teacher takes attendance, all statuses are automatically set to Present. However, when I searched records on a certain date in the database, 2 students were missing records (which isn't even possible unless its being deleted)
Anyone have any idea why this might happen? I've tried replicating it myself (by repeatedly submitting the form, refreshing the page after it's processed, etc, to no avail.)
Thank you for the help!
Your query that check if a record exists is looking for all 3. 1) $studentID, 2) $classid and 3) $classid However the UPDATE statement is just looking for $studentID.
I would suggest you create a PRIMARY KEY (or UNIQUE INDEX) on StudentID,date,classID, then use the MySql INSERT ON DUPLICATE KEY UPDATE...
INSERT INTO attendance_main (StudentID,status,comments,date,classID)
VALUES ('$studentID','$status','$comments','$date','$classid')
ON DUPLICATE KEY UPDATE
status = VALUES(status),
comments = VALUES(comments)
Don't forget to sanitize the database input by using mysql_real_escape_string for example $status = mysql_real_escape_string($_GET[$statusinc]);.