How to avoid duplicate in random query result in mysql - php

I need to select 4 random ids from the table, but problem is that they are sometimes duplicated how to avoid that? I have tried to use DISTINCT but with no results here is the code.As for CMS I am using opencart.
<h1>similar products</h1>
<?php
$id = $this->customer->getCustomerGroupId();
$cur_jur = $this->db->query("SELECT `value` FROM `" . DB_PREFIX . "currency` WHERE currency_id = '1'");
$cur_fiz = $this->db->query("SELECT `value` FROM `" . DB_PREFIX . "currency` WHERE currency_id = '3'");
$max_symb = 25;
$fee_id = $product_id;
$product_sql_test_fee = $this->db->query("SELECT `category_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `product_id`='".$fee_id."' ORDER BY RAND() LIMIT 0,10");
$feed_id = $product_sql_test_fee->row['category_id'];
$i=1;
$imax = 5;
$products_id = '';
while ($i < $imax)
{
$product_fee = $this->db->query("SELECT DISTINCT `product_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `category_id`='".$feed_id."' AND NOT `product_id` = '".$products_id."' GROUP BY `product_id` ORDER BY RAND() LIMIT 0,10");
if(isset($product_fee->row['product_id']))
{
$pr_id[$i] = $product_fee->row['product_id'];
}
$pr_id_[$i] = $this->model_catalog_product->getProduct($pr_id[$i]);
$products_id .= $pr_id[$i].',';
$product_duplicate = explode(',',$products_id);
if ($product_duplicate[$i] == $pr_id[$i])
{
}
//if ($product_duplicate[$i] == $pr_id[$i]){ //echo 'Duplicate';
//continue;} else {
//foreach ($product_duplicate as $id) {
//if ($id == $pr_id[$i]) continue;
//}
//$price_plus = $pr_id_[$i]['price'] + ($pr_id_[$i]['price'] * 0.20);
//$price_minus = $pr_id_[$i]['price'] - ($pr_id_[$i]['price'] * 0.20);
//$price_of_product = (int)$price / $cur_fiz->row['value'];
//if ($price_of_product < $price_plus && $price_of_product > $price_minus) {
//echo $pr_id[$i].'||'.$price_minus.'||'.$price_plus.'||'.$pr_id_[$i]['price'].'||'.$price_of_product.'<br/>';
//}
$price_plus = $pr_id_[$i]['price'] + ($pr_id_[$i]['price'] * 0.30);
$price_minus = $pr_id_[$i]['price'] - ($pr_id_[$i]['price'] * 0.30);
$price_of_product = (int)$price / $cur_fiz->row['value'];
if ($price_of_product < $price_plus && $price_of_product > $price_minus )
{
}
}
?>

You have to use group by category_id problem will be resolved.
SELECT DISTINCT `product_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `category_id`='".$feed_id."' AND NOT `product_id` = '".$products_id."' GROUP BY `category_id`

Related

How to unlink two images from two different folders at once in php

I have this code which is supposed to delete two image files from two diffrent folders at the same time. The issue is, only one image is deleted. the other is not. I have tried different methods but still the same issue.
Below is my code.
<?php
$colname_albumedit = "-1";
if (isset($_GET['arf'])) {
$colname_albumedit = $_GET['arf'];
}
$query_album = "SELECT * FROM galbum WHERE alID = '" . $colname_albumedit . "'";
$result_album = mysqli_query($connKcla, $query_album);
$row_album = mysqli_fetch_assoc($result_album);
$totalRows_album = mysqli_num_rows($result_album);
$query_album_images = "SELECT * FROM gimage WHERE alID = '" . $colname_albumedit . "'";
$result_album_images = mysqli_query($connKcla, $query_album_images);
$row_album_images = mysqli_fetch_assoc($result_album_images);
$totalRows_album_images = mysqli_num_rows($result_album_images);
if ((isset($_POST["form_del"])) && ($_POST["form_del"] == "adalbumdel")) {
$target = "../gallery/albums/";
$targett = "../gallery/images/";
$imID = $_GET['arf'];
$sql_query = "SELECT alImage FROM galbum WHERE alID = $imID";
$photoresult = mysqli_query($connKcla, $sql_query);
$row_album = mysqli_fetch_assoc($photoresult);
if (($row_album['alImage']) != 0) {
unlink($target . $row_album['alImage']);
}
$sql_queryy = "SELECT albumRef FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_assoc($photoresultt);
if (($row_album_images['albumRef']) != 0) {
unlink($targett . $row_album_images['albumRef']);
}
$query_del = "DELETE FROM galbum WHERE alID = $colname_albumedit";
$result_del = mysqli_query($connKcla, $query_del);
$queryy_del = "DELETE FROM gimage WHERE alID = $colname_albumedit";
$resultt_del = mysqli_query($connKcla, $queryy_del);
if ($result_del && $resultt_del) {
$updateGoTo = "confirm.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header("Location: " . $updateGoTo);
} else {
header("Location: error.php");
}
}
The table gImage looks like this:
CREATE TABLE IF NOT EXISTS gimage (
imID bigint(20) NOT NULL AUTO_INCREMENT,
imImage varchar(255) DEFAULT NULL,
albumRef bigint(20) DEFAULT NULL,
PRIMARY KEY (imID), KEY alID (albumRef)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Think, just replace this code
$sql_queryy = "SELECT albumRef FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_assoc($photoresultt);
if (($row_album_images['albumRef']) != 0) {
unlink($targett . $row_album_images['albumRef']);
}
with this code.
$sql_queryy = "SELECT imImage FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_all($photoresultt);
foreach ($row_album_images as $row) {
unlink($targett . $row[0]);
}
Recommendation
Rename your variable $imID cause it is in reality the albumId. As you can see in your code in the lines
$imID = $_GET['arf'];
$sql_query = "SELECT alImage FROM galbum WHERE alID = $imID";

Limit number of database calls within multiple functions

I have created several functions to pull data from a MySQL database.
I have my main query that loops through each horse in a racecard and uses the functions to pull data on that horse. The code that uses the functions is below:
//note I'm using select * until I finish knowing what I need to pull//
$horses12 = mysqli_query($db, 'SELECT * FROM tom_cards');
while($todayhorse12 = mysqli_fetch_array($horses12)){
$horse = $todayhorse12['Horse'];
$distance = $todayhorse12['Distance'];
$trainer = $todayhorse12['Trainer'];
$jockey = $todayhorse12['Jockeys_Claim'];
$weight = $todayhorse12['Weight'];
$class = $todayhorse12['Class'];
//function calls go here e.g
echo $horse.horselargerace($horse,$db)."<br />";
}
The issue as every function calls my database and it either takes forever or connections time out. Below are the functions - can anyone figure out a way to cut down on the number of MySQL connections I need to make?
///////////////////////////////////////////////////////////////////////////////////////
//did the horse run in a large field of 12 or more horses and perform well recently?//
//////////////////////////////////////////////////////////////////////////////////////
function horselargerace($horse, $db)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Runners > 12 ORDER BY Date Limit 5');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$runners = 0;
if ((int) $todayhorse['Place'] < 5) {
$count = $count + 1;
}
}
return $count;
}
//////////////////////////////////////////////////////////////////
//is the horse moving up in class after a good finish or a win?//
////////////////////////////////////////////////////////////////
function horselastclass($horse, $db, $class)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$class2 = trim(str_replace("Class", "", $todayhorse['Class']));
$class = trim(str_replace("Class", "", $class));
if ($class2 == "") {
$class2 = $class;
}
if (trim($class) != "" or trim($class2) != "") {
//if a horse is being dropped in class this should be easier
if ((int) $class < (int) $class2) {
$count = $count + 1;
} elseif ((int) $class > (int) $class2) {
$count = $count - 1;
}
}
}
return $count;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//is the horse picking up or dropping weight today? //
// 114pds or under is ideal.horse drops 5pds or more from the last start i take that as a positive, if he picks up more than 5pds then i consider that a negative.//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function horselastweight($horse, $db, $weight)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$weight2 = preg_replace("/[^a-zA-Z]/", "", $weight);
$weight2 = substr($weight2, 0, 1);
if ($weight2 <> "") {
$weight = substr($weight, 0, strpos($weight, $weight2));
}
//get stone and convert to pounds
$total1 = (((int) substr($weight, 0, strpos($weight, "-"))) * 14) + (int) substr($weight, 1, strpos($weight, "-"));
$total2 = (((int) substr(str_replace(chr(194), "", $todayhorse['Weight']), 0, strpos(str_replace(chr(194), "", $todayhorse['Weight']), "-"))) * 14) + (int) substr(str_replace(chr(194), "", $todayhorse['Weight']), 1, strpos(str_replace(chr(194), "", $todayhorse['Weight']), "-"));
$weight = str_replace(chr(194), "", $todayhorse['Weight']) . "=" . $weight;
}
$total = (int) $total2 - (int) $total1;
if ((int) $total > 4) {
$count = $count + 1;
} elseif ((int) $total < -4) {
$count = $count - 1;
}
return $count;
}
//////////////////////////////////////////////////////////////////////////////
//did the horse have trouble in his/her last race? (comments broke slow ect)//
/////////////////////////////////////////////////////////////////////////////
function horsehavetrouble($horse, $db)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Place'] = "2" or $todayhorse['Place'] = "3" or $todayhorse['Place'] = "4" or $todayhorse['Place'] = "5") {
$targets = array(
"hampered",
"awkward",
"stumbled",
"slipped",
"jinked",
"fell",
"unseated"
);
foreach ($targets as $target) {
if (strstr(strtolower($todayhorse['Comments']), $target) !== false) {
$count = $count + 1;
}
}
}
}
return $count;
}
///////////////////////////////////////////////////////////////
//is the same jockey back on today after not winning in last?//
///////////////////////////////////////////////////////////////
function isjockeyonagainafterlosing($horse, $db, $jockey)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place != "1" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$pop = array_pop(explode(' ', $todayhorse['Jockeys_Claim']));
if (trim(array_pop(explode(' ', $todayhorse['Jockeys_Claim']))) == trim(array_pop(explode(' ', trim($jockey))))) {
$count = $count + 1;
}
}
return $count;
}
//////////////////////////////////////////////////////
//has the jockey won previously on this same horse?//
////////////////////////////////////////////////////
function Hasjockeywonbeforeonhorse($horse, $db, $jockey)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place ="1" ORDER BY Date');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
//get todays jockey and check to see if it matches with prev ones
if (trim(array_pop(explode(' ', $todayhorse['Jockeys_Claim']))) <> trim(array_pop(explode(' ', trim($jockey))))) {
$count = $count + 1;
}
}
return $count;
}
////////////////////////////////////
//is the horse changing trainers?//
//////////////////////////////////
function horsechnagedtrainers($horse, $db, $trainer)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
while ($todayhorse = mysqli_fetch_array($horses)) {
$count = 0;
//compare last trainer and current
if (trim(array_pop(explode(' ', $todayhorse['Trainer']))) <> trim(array_pop(explode(' ', trim($trainer))))) {
$count = $count + 1;
}
}
return $count;
}
///////////////////////////////////////////////
//has the horse won at high odds in the past?//
///////////////////////////////////////////////
function horsehighodds($horse, $db)
{
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place ="1" ORDER BY Date Limit 1');
while ($todayhorse = mysqli_fetch_array($horses)) {
$fraction = str_replace("F", "", $todayhorse['Odds']);
$fraction = str_replace("J", "", $fraction);
$fraction = explode("/", $fraction);
if ($fraction[1] != 0) {
$fraction = ($fraction[0] / $fraction[1]);
}
$fraction = (int) $fraction;
if (in_array((int) $fraction, range(2, 6))) {
$count = $count + 1;
}
}
return $count;
}
///////////////////////////////////////////////////////
//was the horse between 2-1 & 6-1 odds in last start?//
///////////////////////////////////////////////////////
function horsebetween2and6($horse, $db)
{
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
//convert the odds to decimal
$fraction = str_replace("F", "", $todayhorse['Odds']);
$fraction = str_replace("J", "", $fraction);
$fraction = explode("/", $fraction);
if ($fraction[1] != 0) {
$fraction = ($fraction[0] / $fraction[1]);
}
$fraction = (int) $fraction;
if ((int) $fraction <= 2 and (int) $fraction >= 6) {
$count = $count + 1;
}
if (in_array((int) $fraction, range(2, 6))) {
$count = $count + 1;
}
return $count;
}
}
//////////////////////////////////////////////////////
//was this horse a beaten favorite in last 3 starts?//
//////////////////////////////////////////////////////
function horsebeatenfav($horse, $db)
{
$count = 0;
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 3');
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Place'] <> "1" and strpos($todayhorse['Odds'], 'F') !== false) {
$count = $count + 1;
}
}
return $count;
}
////////////////////////////////////////////////
//How many starts has the horse had this year?//
////////////////////////////////////////////////
function startswithin12months($horse, $db)
{
$startdate = date('Y-m-d', strtotime('-1 year'));
$enddate = date('Y-m-d');
$horses = mysqli_query($db, 'SELECT Date FROM horsesrp where Horse = "' . $horse . '" and Date >= "' . $startdate . '" AND Date <= "' . $enddate . '" ORDER BY Date');
return $horses->num_rows;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Is the horse changing distances today? - find out if the horse has ever won at this distance - if not -1point//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function hashorsechangedistance($horse, $distance, $db)
{
//select all distances this horse has run
$horses = mysqli_query($db, 'SELECT Distance FROM horsesrp where Horse = "' . $horse . '" ORDER BY Date');
//count the times its run at this distance
$distancecount = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Distance'] == $distance) {
$distancecount = $distancecount + 1;
}
}
//if distance is greater then 0 its ran at this distance before
return $distancecount;
}
/////////////////////////////////////////////////////////
//How long has the horse been off (time between races)?//
/////////////////////////////////////////////////////////
function horselastrace($horse, $db)
{
//select horse last run
$sql = 'SELECT `Date` FROM `horsesrp` where `Horse` = "' . $horse . '" ORDER BY Date limit 1';
$horses = mysqli_query($db, $sql);
while ($todayhorse = mysqli_fetch_array($horses)) {
$dStart = new DateTime($todayhorse['Date']);
$dEnd = new DateTime(date('Y-m-d'));
$dDiff = $dStart->diff($dEnd);
return $dDiff->days;
}
}
Queries grouped together will be as follows:
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$sql = 'SELECT `Date` FROM `horsesrp` where `Horse` = "'.$horse.'" ORDER BY Date limit 1';
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place != "1" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place ="1" ORDER BY Date');
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place ="1" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 3');
$horses = mysqli_query($db, 'SELECT Date FROM horsesrp where Horse = "'.$horse.'" and Date >= "'.$startdate.'" AND Date <= "'.$enddate.'" ORDER BY Date');
$horses = mysqli_query($db, 'SELECT Distance FROM horsesrp where Horse = "'.$horse.'"');
Table structure:
Field
Type
Null
Key
Default
Extra
ID
int(255)
NO
PRI
NULL
auto_increment
ParentID
int(255)
NO
NULL
Date
date
NO
NULL
Track
varchar(100)
YES
NULL
Runners
varchar(50)
YES
NULL
Going
varchar(50)
YES
NULL
Distance
varchar(50)
YES
NULL
Class
varchar(50)
YES
NULL
Place
varchar(10)
YES
NULL
Losing_Dist
varchar(50)
YES
NULL
Stall
varchar(250)
YES
NULL
Horse
varchar(50)
YES
NULL
Weight
varchar(50)
YES
NULL
Trainer
varchar(50)
YES
NULL
Odds
varchar(50)
YES
NULL
Oddsmovement
varchar(250)
NO
NULL
Jockeys_Claim
varchar(50)
YES
NULL
Comments
varchar(250)
YES
NULL
Race_Name
varchar(250)
YES
NULL
Timetaken
varchar(255)
NO
NULL
OR
varchar(6)
NO
NULL
Do you have index on field Horse in table horsesrp? Specified queries should be processed fast, even with large dataset. You can do this as follows:
ALTER TABLE horsesrp ADD INDEX Horse (Horse);
More on MySQL Indexes:
http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html
How do MySQL indexes work?

Avoiding hard coded nested foreach loops

Is there any way I can avoid doing this (which is looping through directory data in a database, and then getting the same data for all it's children, and childrens children... ad infinitum:
$directories = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `level` = '1' AND `batch` = %s", $lastBatchID);
foreach ($directories as $dir) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir");
$size = intval($dirInfo[0]['size']) * 1024;
echo stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories2 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir, $lastBatchID);
foreach ($directories2 as $dir2) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir2");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories3 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir2, $lastBatchID);
foreach ($directories3 as $dir3) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir3");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories4 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir3, $lastBatchID);
foreach ($directories4 as $dir4) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir4");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories5 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir4, $lastBatchID);
foreach ($directories5 as $dir5) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir5");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
}
}
}
}
}
Basically we are getting data for x number of levels of directories, and need a loop for each of the levels to display the data as follows:
C:\it\AD-Chris Integration -Current:49.70M
=>C:\it\AD-Chris Integration\AD-Chris2 -Current:49.69M
=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris -Current:5.22M
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Common -Current:599.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Department -Current:453.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Encrypt -Current:327.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Location -Current:387.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Manager -Current:1.36M
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\ScanForStaffID -Current:348.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Title -Current:498.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\bin -Current:529.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\obj -Current:439.00K
=>=>C:\it\AD-Chris Integration\AD-Chris2\_Deploy -Current:622.00K
I have a variable available which has the number of levels deep we need to go
function something($dir, $lastBatchID, $level = 0) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir");
$size = intval($dirInfo[0]['size']) * 1024;
echo str_repeat('=>', $level);
echo stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories2 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir, $lastBatchID);
if ($level > 5) return;
foreach ($directories2 as $dir2) {
something($dir2, $lastBatchID, $level + 1);
}
}
$directories = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `level` = '1' AND `batch` = %s", $lastBatchID);
foreach ($directories as $dir) {
something($dir, $lastBatchID);
}

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

Can't figure out duplicate entries for data in SQL field, and random cell deletion (PHP/MYSQL)

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

Categories