two methods in a class so close in what they do - php

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
}

Related

"SQL translate error: Extra placeholder" when using prepared statements

I'm trying to use prepared statements in my SQL but I can't get it working. I'm getting error "SQL translate error: Extra placeholder" when I add something like this to my code
if ($cpucooler_socket != "") {
$myArray = explode(',', trim($cpucooler_socket));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$socket = $myArray[$i];
if ($i === 0) {
$query .= " AND (socket LIKE ?";
$query_params[] = '%' . $socket . '%';
} else if ($i === count($myArray) - 1) {
$query .= " OR socket LIKE ?)";
$query_params[] = '%' . $socket . '%';
} else {
$query .= " OR socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
} else {
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
}
}
What am I doing wrong? What is the right syntax that I should be using in this case? If I don't use the for loop and I add only for example this instead:
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $myArray[0] . '%';
then it's working fine. Here is my full code if it helps:
public function getCompatibleMb($case_format_dosky, $cpu_socket, $ram_typ, $pocet_ram, $intel_socket, $amd_socket, $select_after_id, $search) {
$cpucooler_socket = null;
if(isset($intel_socket) || isset($amd_socket)){
if ($intel_socket != null && $amd_socket != null) {
$cpucooler_socket = $intel_socket.", ".$amd_socket;
} else if($intel_socket != null) {
$cpucooler_socket = $intel_socket;
} else if ($amd_socket != null){
$cpucooler_socket = $amd_socket;
}
} else {
$cpucooler_socket = null;
}
$query_params = array();
$query = "SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1";
if ($cpu_socket != "") {
$query .= " AND socket = ?";
$query_params[] = $cpu_socket;
} else {
if ($cpucooler_socket != "") {
$myArray = explode(',', trim($cpucooler_socket));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$socket = $myArray[$i];
if ($i === 0) {
$query .= " AND (socket LIKE ?";
$query_params[] = '%' . $socket . '%';
} else if ($i === count($myArray) - 1) {
$query .= " OR socket LIKE ?)";
$query_params[] = '%' . $socket . '%';
} else {
$query .= " OR socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
} else {
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
}
}
}
if ($ram_typ != "") {
$query .= " AND ram_type = ?";
$query_params[] = $ram_typ;
}
if ($pocet_ram != "") {
$query .= " AND ram_slots >= ?";
$query_params[] = $pocet_ram;
}
if($case_format_dosky !="") {
$myArray = explode(',', trim($case_format_dosky));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$formfactor = trim($myArray[$i]);
if ($i === 0) {
$query .= " AND (form_factor = ?";
$query_params[] = $formfactor;
} else if ($i === count($myArray) - 1) {
$query .= " OR form_factor = ?";
$query_params[] = $formfactor;
} else {
$query .= " OR form_factor = ?)";
$query_params[] = $formfactor;
}
} else {
$query .= " AND form_factor LIKE ?";
$query_params[] = '%' . $formfactor . '%';
}
}
}
if ($select_after_id != "") {
$decrypted = $this->McryptServices->decryptData($select_after_id);
$query .= " AND id > ?";
$query_params[] = $decrypted;
}
if ($search != "") {
$new_search = str_replace(" ", "%",$search);
$query .= " AND produkt LIKE ?";
$query_params[] = '%'.$new_search.'%';
}
$query .= " LIMIT 32";
$vytah = $this->Database->query($query, $query_params)->fetchAll();
$arr[] = $vytah;
foreach ($arr[0] as $key => $value) {
$arr[0][$key]->{'encryptid'} = $this->McryptServices->encryptData($arr[0][$key]->{'id'});
}
return json_encode($arr);
}
This is the response after an error:
"line":225,"args":[["string","SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1 AND (form_factor = ? OR form_factor = ? OR form_factor = ?) LIMIT 32"],["array",[["string","ATX"],["string","mATX (Micro ATX)"],["string","mITX (Mini ITX)"]]]]}

PHP MySQL Advance Search with Check boxes

I am trying to build search logic that uses multiple form fields and adjusts the MySQL search accordingly. My main area of issue is when dealing with multiple checkboxes. The below gets me close but I get multiple "OR" at the end for some reason. The below gives me (nema = '1' OR OR nema = '12' OR OR nema = '4' OR OR ) for example. More OR's are added for each checkbox. What am I missing or not doing correctly?
$rating = mysqli_real_escape_string($db, implode(',', $_POST['rating']));
$q = "SELECT * FROM lekker WHERE height BETWEEN 20 AND 30 ";
if (!empty($rating)) {
$var = explode(',',$rating);
$rating_count = count($var);
if($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test'";
for($i=0;$i<$rating_count;$i++) {
if($i!=$rating_count-1) {
$q .= " OR ";
}
}
}
$q .= " )";
} else {
$q .= "nema = '$rating'";
}
}
$q .= " ORDER BY `part` ASC";
This is the Select I am trying to achieve:
SELECT * FROM lekker WHERE height BETWEEN 20 AND 22 AND (nema = '1' OR nema = '12') ORDER BY part ASC
I removed the second loop and always add OR, then you can remove the last one at the end
$rating = mysqli_real_escape_string($db, implode(',', $_POST['rating']));
$q = "SELECT * FROM lekker WHERE height BETWEEN 20 AND 30 ";
if (!empty($rating)) {
$var = explode(',',$rating);
$rating_count = count($var);
if($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test' OR ";
}
$q=substr($q, 0,-4);
$q .= " )";
} else {
$q .= "nema = '$rating'";
}
}
$q .= " ORDER BY `part` ASC";
Instead of worrying about whether or not you need to add an OR simply add it each time through your foreach then trim off the trailing OR after you are done with the foreach.
if ($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test' OR ";
}
$q .= rtrim($q,' OR ') . ' )';
} else {
$q .= "nema = '$rating'";
}

joomla k2 tag cloud random

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;
}
}

array pulling out no results

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'].

Only displaying the last record of the array PHP

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);

Categories