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?
Related
User will enter like more than one payment card 1.00,cash 2.00,card 10,00,cash 20.00 etc...After these all values insert into payment_details table one by one along with current date.So after this i need to insert data to another table called moneybox table.
Count of total cash and total card will store into money box group by current date.Always two rows ie; card and cash will be there in money table,going to total of cash and card will be store based on current date.
As far as I understand the requirements, this may help...
<?php
if (isset($_POST["getamount"])) {
$getinvoiceid = $_POST['getinvoiceid'];
$getstorepaymode = $_POST['getstorepaymode'];
$getamount = $_POST['getamount'];
$sql1 = "select date from moneybox order by ID desc limit 1";
$result1 = mysqli_query($link, $sql1);
$row1 = mysqli_fetch_array($result1);
//echo json_encode($row1);
$last_moneybox_created_date = $row1['date'];
$sqlclosebalcash = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='cash'";
$resultclosebal_cash = mysqli_query($link, $sqlclosebalcash);
$rowclosebal_cash = mysqli_fetch_array($resultclosebal_cash);
//echo json_encode($row1);
//$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
$sqlclosebalcard = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='bank'";
$resultclosebal_card = mysqli_query($link, $sqlclosebalcard);
$rowclosebal_card = mysqli_fetch_array($resultclosebal_card);
//$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
$tz = 'Asia/Dubai'; // your required location time zone.
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$todayDate = $dt->format('Y-m-d');
if ($rowclosebal_cash['closing_balance'] == '') {
$last_moneybox_closingbalanacecash = "0.00";
} else {
$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
}
if ($rowclosebal_card['closing_balance'] == '') {
$last_moneybox_closingbalanacecard = "0.00";
} else {
$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
}
for ($count = 0; $count < count($getamount); $count++) {
$payamt_clean = $getamount[$count];
$getstorepaymode_clean = $getstorepaymode[$count];
date_default_timezone_set('Asia/Dubai');
$created = date("y-m-d H:i:s");
$query = 'INSERT INTO payment_details (invoiceID,paymentMode,Amount,created)
VALUES ("' . $getinvoiceid . '" , "' . $getstorepaymode_clean . '", "' . $payamt_clean . '", "' . $created . '");
';
mysqli_query($link, $query);
// check whether card or cash or both rows are already there or not
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='cash' ";
$resultcash = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcash)) {
$cashMode = 1;
}
else {
$cashMode = 0;
}
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='bank' ";
$resultcard = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcard)) {
$cardMode = 1;
}
else {
$cardMode = 0;
}
$cal_closingbalancecash = $last_moneybox_closingbalanacecash - $payamt_clean;
$cal_closingbalancecard = $last_moneybox_closingbalanacecard - $payamt_clean;
switch($getstorepaymode_clean) {
case "CASH":
if($cashMode === 0) {
echo 'Different Date cash'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cashMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('cash','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date cash'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'cash' and date = '$todayDate';";
}
break;
case "CARD":
if($cardMode === 0) {
echo 'Different Date card'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cardMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('bank','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date card'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'bank' and date = '$todayDate';";
}
break;
} // end switch case
if (mysqli_query($link, $query)) {
echo 'paydetails Inserted';
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($link);
}
}
}
?>
I have a search form in a website and would like to have several search terms which is input by the user to perform db search, terms as below:
Keywords
Property For (Sale, Rent...)
Property Type (Apartment, Terrace House...)
State
Min Price
Max Price
Here is script to perform search with above term's input
public function get_property_list_by_search($start, $per_page, $keyword, $prop_for, $min, $state, $ptype, $max, $mysqli)
{
if(empty($start) && empty($per_page))
{
return 0;
}
$start = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($start));
$per_page = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($per_page));
$keyword = $mysqli->real_escape_string(stripslashes($keyword));
$prop_for = $mysqli->real_escape_string(stripslashes($prop_for));
$state = $mysqli->real_escape_string(stripslashes($state));
$ptype = $mysqli->real_escape_string(stripslashes($ptype));
$min_price = self::num_clean($mysqli->real_escape_string($min));
$max_price = self::num_clean($mysqli->real_escape_string($max));
$t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
if(isset($keyword) && !empty($keyword)){
$t1 = " AND `proj_title` LIKE '%".$keyword."%' OR `proj_addr` LIKE '%".$keyword."%' OR `proj_area` LIKE '%".$keyword."%'";
}
if(isset($prop_for) && !empty($prop_for)){
$t2 = " AND `proj_for`='".$prop_for."'";
}
if(isset($state) && !empty($state)){
$t3 = " AND `state`='".$state."'";
}
if(isset($ptype) && !empty($ptype)){
$t4 = " AND `proj_cat`='".$ptype."'";
}
//min & max
if((isset($min_price) && !empty($min_price)) && (isset($max_price) && !empty($max_price))){
$t5 = " AND `price` BETWEEN '".$min_price."' AND '".$max_price."'";
}
//min only
if(!empty($min_price) && empty($max_price)){
$t5 = " AND `price` >= '".$min_price."'";
}
//max only
if(empty($min_price) && !empty($max_price)){
$t5 = " AND `price` <= '".$max_price."'";
}
$sql = $mysqli->query("SELECT * FROM `project` WHERE `status`='1' ".
$t1." ".$t2." ".$t3." ".$t4." ".$t5." ".
"ORDER BY `posted_date` DESC LIMIT ".$start.", ".$per_page);
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
The query output will something like:
SELECT * FROM `project`
WHERE `proj_title` LIKE '%keywords%'
OR `proj_addr` LIKE '%keywords%'
OR `proj_area` LIKE '%keywords%'
AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
(Datatype for price is DECIMAL(10,2), it stored value like 250000.00)
However, the returned results is not like expected (not accurate), its also will come out a result with price more than 600000 and project category which is out of '8' which is not fancy for the end user to searching in the website.
is there any way to refine on the query to perform more specific?
Instead of taking these variables you should use ".=" operator.
/* $t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
*/
$q = "SELECT * FROM `property` WHERE `status`='1' ";
// You need to enclose all **OR** logical tests in parenthesis.
// Moreover most of the usages of isset function are useless,
// as your are initializing many variables
if($keyword && !empty($keyword)){
$q .= " AND (`p_title` LIKE '%".$keyword."%' OR `address` LIKE '%".$keyword."%' OR `area` LIKE '%".$keyword."%')";
}
if($prop_for && !empty($prop_for)){
// If you are using double quotes you really don't need handle to concatenation.
$q .= " AND `p_for`='$prop_for'";
}
if($state && !empty($state)){
$q .= " AND `state`='$state'";
}
if($ptype && !empty($ptype)){
$q .= " AND `p_category`='$ptype'";
}
//min only
if($min_price && !empty($min_price)){
$q .= " AND `price` >= '".$min_price."'";
}
//max only
if($max_price && !empty($max_price)){
$q .= " AND `price` <= '$max_price'";
}
// When you are not using OFFSET keyword,
//the first number after LIMIT keyword should be the number of records
$q .= " ORDER BY `posted_date` DESC LIMIT $per_page , $start;";
$sql = $mysqli->query($q);
You're going to need parentheses.
SELECT * FROM `project` WHERE (`proj_title` LIKE '%keywords%' OR `proj_addr` LIKE '%keywords%' OR `proj_area` LIKE '%keywords%') AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
Without the parentheses it just has to match one of the criteria before the last OR.
if(isset($_SESSION['login']))
{
echo "<div align=\"right\"><strong> Home |
Signout|
Profile</strong></div>";
}
else
{
echo " ";
}
$con= mysql_connect("localhost","root","");
$d=mysql_select_db("matrimonial",$con);
$gender=$_POST['gender'];
$age1=$_POST['age1'];
$age2=$_POST['age2'];
$city=$_POST['city'];
$subcast=$_POST['subcast'];
$result=mysql_query("select * from matri where gender='$gender' and age between '$age1' and '$age2' and city='$city' and subcast='$subcast'");
if($gender && !empty($gender))
{
$result .= " AND `gender`='$gender'";
}
if($age1 && !empty($age1)){
$result .= " AND `age`='$age1'";
}
if($age2 && !empty($age2)){
$result .= " AND `age`='$age2'";
}
if($city && !empty($city)){
$result .= " AND `city`='$city'";
}
if($subcast && !empty($subcast)){
$result .= " AND `subcast`='$subcast'";
}
$result .= " select * from ";
$sql = $mysql->query($result);
how to run this code
On the price difference you should do a if the price if between the 2 values else only 1 value.
I am trying to create a tracker code, which is when a user enter my page, I will record and add the visitor view by 1
The problem with my code is on every monday, it not only reset the week stats, it also reset the month stats, I paste my increment code and reset code in php below.
Thanks for helping me, I try to figure it out for a few days but can't spot where I code wrongly.
This is my ads.php which I run it by do
<img src="ads.php" width="1" height="1">
at every page
This is my ads.php code
include 'conn.php';
$postID = $_GET['pid'];
$todayDate = date("m-d-y");
//Query with postDate
$sql = "SELECT * FROM wp_tracker WHERE postID LIKE '" . $postID . "'";
$result = mysql_query($sql);
$exist = 0;
while ($row = mysql_fetch_array($result)) {
$postDate = $row['postDate'];
$dayView = $row['dayView'];
$weekView = $row['weekView'];
$monthlyView = $row['monthlyView'];
$exist++;
}
if ($exist == 0) {
//create new record
$sql = "INSERT INTO wp_tracker (postID, postDate) VALUES ('$postID ','$todayDate')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
}
if ($exist > 0) {
//if record exist
//check if it same day
if ($postDate == $todayDate) {
//if same day - just increment views
$dayView = $dayView + 1;
$weekView = $weekView + 1;
$monthlyView = $monthlyView + 1;
$sql2 = "UPDATE wp_tracker SET dayView = '$dayView',weekView = '$weekView',monthlyView = '$monthlyView' WHERE postID='$postID '";
$result2 = mysql_query($sql2);
}
}//end if exist
Below is my reset code (reset.php)
$todayDate = date("m-d-y");
//Query with postDate
$sql = "SELECT postDate FROM wp_tracker order by postDate ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$postDate = $row[0];
$timestamp = time();
if ($postDate != $todayDate) {
//a new day -- update dayView to 0
$dayView = 1;
$sql3 = "UPDATE wp_tracker SET postDate= '" . $todayDate . "', dayView = '$dayView'";
$result3 = mysql_query($sql3);
}
if (date('D', $timestamp) === 'Mon') {
$weekView = 1;
$sql3 = "UPDATE wp_tracker SET weekView = '$weekView'";
$result3 = mysql_query($sql3);
}
if (date('d', $timestamp) === '01') {
$monthlyView = 1;
$sql3 = "UPDATE wp_tracker SET monthlyView= '$monthlyView'";
$result3 = mysql_query($sql3);
}
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`
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'].