MySQL Join Queries - php

I've been given this code to work with, and I know that mysql_* is deprecated, but I'm trying to figure out a way to join all of these queries, because these while loops and queries are hogging resources and killing load time. Any suggestions?
$result2 = mysql_query("SELECT * FROM tblOperators WHERE (Team = 'SALES' OR Team = 'RENEWALS' OR Team = 'CSR') AND OperatorLocale='USA' AND OperatorStatus='ACTIVE'");
while ($row2 = mysql_fetch_array($result2)) {
$operID = $row2['OperatorID'];
$result = mysql_query("SELECT * FROM tblUserPayments WHERE OperatorID = '$operID' AND PaymentStatus='OK' AND PaymentDate LIKE '$currentDate%'");
while ($row = mysql_fetch_array($result)) {
if ($row['PaymentReason'] == 'ACTIVATION') {
$ActvCount++;
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$ActvUpgrade += $row['ChargeAmount'];
}
} elseif ($row['PaymentReason'] == 'UPGRADE') {
$userid = $row['UserID'];
$paymentdate = $row['PaymentDate'];
$result1 = mysql_query("SELECT * FROM tblRenewalInvoices WHERE UserID='$userid' AND ('$paymentdate' >= DATE_SUB(DueDate, INTERVAL 90 DAY) AND '$paymentdate' < DATE_ADD(DueDate, INTERVAL 15 DAY)) AND ParentInvoiceID IS NULL ORDER BY InvoiceNum DESC LIMIT 1");
if ($row1 = mysql_fetch_array($result1)) {
$packageid = $row['PackageID'];
$pack = mysql_query("SELECT * FROM tblUserPackages WHERE PackageID='$packageid';");
if ($pack1 = mysql_fetch_array($pack)) {
$expDate = $pack1['ExpirationDate'];
$dueDate = $row1['DueDate'];
$days = mysql_fetch_row(mysql_query("SELECT TO_DAYS('$expDate')-TO_DAYS('$dueDate');"));
$months = (int) (((int) $days + 14) / 30.4);
$years = (int) (((int) $days + 182) / 365);
$Intervals = 0;
if ($years > 0) {
$Intervals = $years;
} if (($pack1['Package'] or 'GPS-SVL') or ($pack1['Package'] == 'GPS-1') or ($pack1['Package'] == 'GPS-1PLUS')) {
if ($Intervals > 1) {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$renewalCount++;
$Actv += $row['ChargeAmount'];
}
} else {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$renewalCount++;
$ActvRenewal += $row['ChargeAmount'];
}
}
} else {
$renewalCount++;
$Actv += $row['ChargeAmount'];
}
} else {
}
} else {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK')
$ActvUpgrade += $row['ChargeAmount'];
}
} elseif ($row['PaymentReason'] == 'ADDVEHICLE') {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK')
$ActvVehicleAdds += $row['ChargeAmount'];
}
}
$result = mysql_query("SELECT * FROM tblRenewalCalls WHERE OperatorID = '$operID' AND PayStatus='OK' AND DateSubmitted LIKE '$currentDate%'");
while ($row = mysql_fetch_array($result)) {
if ($row['Charged']) {
if ((int) $row['RenewYears'] > 1) {
$renewalCount++;
$Actv += $row['RenewTotal'];
} else {
$renewalCount++;
$ActvRenewal += $row['RenewTotal'];
}
}
}
} if ($ActvCount != 0) {
$PerActv = ($ActvUpgrade + $ActvVehicleAdds) / $ActvCount;
} else {
$PerActv = 0;
}
$total = $Actv + $ActvRenewal + $ActvUpgrade + $ActvVehicleAdds;
// Fix to show proper renewal dollars
$ActvRenewal = $total - ($ActvVehicleAdds + $ActvUpgrade);
$AvgRenewal = ($ActvRenewal) / $renewalCount;
$upgradeEarned = $ActvUpgrade;
$renewalEarned = $ActvRenewal;
Here is my code so far for the joined query, but it's not correct because I am still missing certain bits of information. It is much faster for mysql to handle the mathematics, than for the database to pass the information to php, then have php process it. I'm just not sure as to how to approach this:
$result = mysql_query(
"SELECT p.PaymentReason AS PaymentReason,
p.PaymentMethod AS PaymentMethod,
p.ChargeAmount AS ChargeAmount,
p.UserID AS UserID,
p.PaymentDate AS PaymentDate,
r.PackageID AS PackageID
FROM tblOperators AS o JOIN tblUserPayments AS p JOIN tblRenewalInvoices
AS r JOIN tblUserPackages AS k JOIN tblRenewalCalls
AS c ON o.OperatorID=p.OperatorID
AND r.UserID=p.UserID AND r.PaymentDate=p.PaymentDate
AND r.PackageID=k.PackageID
WHERE (o.Team='SALES' OR o.Team='RENEWALS' OR o.Team='CSR') AND
o.OperatorLocale='USA' AND
o.OperatorStatus='ACTIVE' AND
p.PaymentStatus='OK' AND
p.PaymentDate LIKE '$currentDate%'");
Any help is greatly appreciated.

Try this:: You have missed the JOIN Criteria for Table tblRenewalCalls
SELECT p.PaymentReason AS PaymentReason,
p.PaymentMethod AS PaymentMethod,
p.ChargeAmount AS ChargeAmount,
p.UserID AS UserID,
p.PaymentDate AS PaymentDate,
r.PackageID AS PackageID
FROM tblOperators AS o
JOIN tblUserPayments AS p ON o.OperatorID=p.OperatorID
JOIN tblRenewalInvoices AS r ON r.UserID=p.UserID AND r.PaymentDate=p.PaymentDate
JOIN tblUserPackages AS k ON r.PackageID=k.PackageID
JOIN tblRenewalCalls AS c // JOIN CRITERIA
WHERE (o.Team='SALES' OR o.Team='RENEWALS' OR o.Team='CSR') AND
o.OperatorLocale='USA' AND
o.OperatorStatus='ACTIVE' AND
p.PaymentStatus='OK' AND
p.PaymentDate LIKE '$currentDate%'")

Related

Nested if conditions doesn't work

I have nested if conditions on my project but i have a problem;
if(isset($_GET['q']) && isset($_GET['t'])) {
$query = $_GET['q'];
$type = $_GET['t'];
$none_key = FALSE;
if($type = 'singer') {
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%'");
$control = $singers->rowCount();
if($control > 0) {
$on_page = 24;
$number_singers = $singers->rowCount();
$number_page = ceil($number_singers/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%' ORDER BY singer_name ASC LIMIT ".$limit.",".$on_page);
$singer_key = TRUE;
} else {
$none_key = TRUE;
}
}
if($type = 'song') {
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%'");
$control = $songs->rowCount();
if($control > 0) {
$on_page = 24;
$number_songs = $songs->rowCount();
$number_page = ceil($number_songs/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%' ORDER BY song_name ASC LIMIT ".$limit.",".$on_page);
$song_key = TRUE;
} else {
$none_key = TRUE;
}
}
} else {
$key = TRUE;
}
When I run the code, I am expecting that if one of the'control' variables is bigger than 0 the 'none_key' variable must be equal to 0. When the 'type' varible is 'song' there is no problem but if the 'type' variable is 'singer' then 'none_key' variable printing 1, I think it is running the second if block and becomes 'none_key' 1 because of the second 'control' variable is not bigger than zero.
This is an assignment, it sets $type to the value singer:
if ($type = 'singer') {
You want a comparison, it checks to see if $type equals the value singer:
if ($type == 'singer') {
[Edit] Some people prefer to write this sort of statement with the variable last. This is commonly called a "Yoda condition":
if ('singer' == $type) {
This way, if you screw up and only use one =, you get an error.

Sum from column score if column score calculating from other column

Hello I have a table KPI and I want to calculate the final score from this category perspective in KPI (see image)
I script manually to keep the score column dynamic update, but I need to script total score to make my bar gauges up and down automatic.
This is my some code:
$kc= mysql_query("SELECT * FROM kpidetindv WHERE
idCat='3' AND year='$yr' AND vis='0' AND idEmp='$np' ORDER BY code ASC");
While ($kc2= mysql_fetch_assoc($kc))
{
$ikdi = $kc2['idKpiDetIndv'];
$ic = $kc2['idCat'];
$iu = $kc2['idUnit'];
$ictg= mysql_query("select * from `kpicat` where idCat='$ic'") or die(mysql_error());
$ictg2= mysql_result($ictg, 0, 'code');
$imt= mysql_query("select * from `kpiunit` where idUnit='$iu'") or die(mysql_error());
$imt2= mysql_result($imt, 0, 'code');
$imt3= mysql_result($imt, 0, 'symbol');
$sum = mysql_query("SELECT sum(actual) FROM monthkpimontindv WHERE idKpiDetIndv='$ikdi'") or die(mysql_error());
while ($row = mysql_fetch_array($sum)) {
$mkmi= $row['sum(actual)']; }
if ($mkmi=='') { $mkmi2='0';} else { $mkmi2=$mkmi; }
$tg= $kc2['target'];
$scr= $mkmi/$tg;
$scr2= number_format($scr * 100, 0);
$wgh= $kc2['weight'];
$scr3= $scr2*$wgh/100;
$trd= mysql_query("select * from `monthkpimontindv` where idKpiDetIndv='$ikdi' order by idMontIndv desc limit 1") or die(mysql_error());
$trd2= mysql_result($trd, 0, 'actual');
$trd3= mysql_query("select * from `monthkpimontindv` where idKpiDetIndv='$ikdi' order by idMontIndv desc limit 1,1") or die(mysql_error());
$trd4= mysql_result($trd3, 0, 'actual');
if ($trd2 > $trd4 ) { $trd5="trendup.png"; }
else if ($trd2 < $trd4 ) { $trd5="trenddown.png"; }
else if ($trd2 == $trd4 ) { $trd5="trendnet.png"; }
echo '<tr>';
echo '<td>'.$kc2['code'];
echo '<td>'.$kc2['title'].'';
echo '<td>'.number_format($kc2['target']).' '.$imt3;
echo '<td>'.number_format($mkmi2).' '.$imt3;
echo '<td>'.$kc2['weight'];
echo '<td>'.number_format($scr3, 0);
echo '<td class="text-center"><img class=user-avatar src=assets/img/'.$trd5.'>';
echo '<td class="text-center"><i class="fa-edit s16"></i> | </i>';
<?PHP
$kc= mysql_query("SELECT * FROM kpidetindv WHERE idCat='$qki7' AND year='$yr' AND vis='0' AND idEmp='$np' ORDER BY code ASC");
While ($kc2= mysql_fetch_assoc($kc))
{
$sum = mysql_query("SELECT sum(actual) FROM monthkpimontindv WHERE idKpiDetIndv='$q'") or die(mysql_error());
while ($row = mysql_fetch_array($sum)) {
$mkmi= $row['sum(actual)']; }
if ($mkmi=='') { $mkmi2='0';} else { $mkmi2=$mkmi; }
$tg= $kc2['target'];
$scr= $mkmi/$tg;
$scr2= number_format($scr * 100, 0);
$wgh= $kc2['weight'];
$scr3= $scr2*$wgh/100;
$fscr+= number_format($scr3, 0);
}
if ($fscr == 0) { $imgs="speedo.png";}
else if ($fscr <= 10 ) { $imgs="speedo1.png";}
else if ($fscr <= 20 ) { $imgs="speedo2.png";}
else if ($fscr <= 30 ) { $imgs="speedo3.png";}
else if ($fscr <= 40 ) { $imgs="speedo4.png";}
else if ($fscr <= 50 ) { $imgs="speedo5.png";}
else if ($fscr <= 60 ) { $imgs="speedo6.png";}
else if ($fscr <= 70 ) { $imgs="speedo7.png";}
else if ($fscr <= 80 ) { $imgs="speedo8.png";}
else if ($fscr <= 90 ) { $imgs="speedo9.png";}
else if ($fscr <= 1000 ) { $imgs="speedo10.png";}
?>

Sum values in each group with a loop

I have a while loop that gives this result:
Userid Point
1 10
1 15
2 5
2 10
3 8
3 2
How can I sum the userid points and output with highest number first, like this:
Userid Point
1 25
2 20
3 10
Is there any "foreach", "for" or any other method that can accomplish such result?
The code:
include ('variables.php');
//Fetch data from matchdata table
$q = "SELECT userid, matchid, homescore, awayscore FROM predictiondata ORDER BY userid ASC";
$r = mysqli_query($mysqli, $q);
while ($row = mysqli_fetch_array($r)) {
//Define predictions
$predhome = $row['homescore'];
$predaway = $row['awayscore'];
//Fetch gameresults
$qres = "SELECT id, homescore, awayscore, bonuspoints FROM matches WHERE id = ".$row['matchid']."";
$rres = mysqli_query($mysqli, $qres);
$result = mysqli_fetch_array($rres);
$homescore = $result['homescore'];
$awayscore = $result['awayscore'];
$bonus = $result['bonuspoints'];
$id = $result['id'];
//Calculate points
if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $result_point = $correct_score + $correct_result + $correct_number + $correct_number; }
else if ($homescore == $predhome && $awayscore != $predaway OR $homescore != $predhome && $awayscore == $predaway) { $result_point = $correct_result + $correct_number; }
else if ($predhome > $predaway && $homescore > $awayscore OR $predhome < $predaway && $homescore < $awayscore) { $result_point = $correct_result; }
else if (is_null($predhome) OR $homescore == '') { $result_point = 0; }
else { $result_point = 0; }
if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $bonus = $bonus; }
else if (is_null($predhome) OR $homescore == '') { $bonus = 0; }
else { $bonus = 0; }
if (is_null($predhome) OR $homescore == '') { $total_point = 0; }
else { $total_point = $result_point + $bonus; }
//Calculate total round sum
$total_roundsum = $result_point + $bonus;
//echo $username.' - '.$total_roundsum.'<br />';
if($total_roundsum != 0) {
echo $row['userid']. ' - ' .$total_roundsum.'<br />';
}
}
At the moment, the code only echo's the results.
The "variables.php" holds the $correct_score + $correct_result + $correct_number variables.
Assuming the two columns are an associated array -- $users_and_points.
$points_array = array();
foreach ( $users_and_points as $user_id => $point ) {
if( !isset( $points_array[$user_id] ) {
$points_array[$user_id] = 0;
}
$points_array[$user_id] += $point;
}
// newly associated array with calculated totals
$points_array;
Update
Based on your code above instead of echoing build an array of users and points.
echo $row['userid']. ' - ' .$total_roundsum.'<br />';
can be replaced with:
if( !isset( $points_array[$row['userid']] ) {
$points_array[$row['userid']] = 0;
}
$points_array[$row['userid']] += $total_roundsum;
That will give you an associated array of user ids and associated points.
print_r( $points_array );
Note: Set the variable before your loop. Example, $points_array = array();

SQL: Unix Timestamp entrys with Zero

i misunderstand why my query gives me entrys with an Timestamp of 0. Can anyone say me what im doing wrong?
Query:
SELECT
*
FROM
`changes`
WHERE
`time_from`>=1393628400
AND
`time_to`<=1394838000
AND
`area`='USERNAME'
ORDER BY
`time_from` DESC,
`time_to` DESC
PHP
$time_from = (isset($_POST['time_from']) ? strtotime($_POST['time_from']) : null);
$time_to = (isset($_POST['time_to']) ? strtotime($_POST['time_to']) : null);
if(empty($time_from) && empty($time_to)) {
/* Do Nothing */
} else {
if(!empty($time_from) && $time_from > 0 && !empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_from`>=%d AND `time_to`<=%d', $time_from, $time_to);
} else if(!empty($time_from) && $time_from > 0) {
$query = sprintf(' `time_from`>=%d', $time_from);
} else if(!empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_to`<=%d', $time_to);
}
$results = $wpdb->get_row(sprintf('SELECT COUNT(*) AS `count` FROM `%sarea_changes` WHERE%s AND `area`=\'%s\'', $wpdb->prefix, $query, $user->user_login));
$count = $results->count;
if($count < 10) {
$position = 0;
$has_more_pages = false;
}
$pages = ceil($count / $max_rows);
$query = sprintf('SELECT * FROM `%sarea_changes` WHERE%s AND `area`=\'%s\' ORDER BY `time_from` DESC, `time_to` DESC', $wpdb->prefix, $query, $user->user_login, $position, $max_rows);
print $query;
$entrys = $wpdb->get_results($query); // LIMIT %d, %d
}
POST Data:
time_from is 01.03.2014 and time_to is 15.03.2014
But i get following entrys (see the time_to), why is that 0 that dont match my Query?
Screenshot:
(Hidden data for privacy policy)

Search gives only one element from set

There is a small problem. I have this 3 functions, and this functions make search in DB. But, that search give only one element from category (when we have 2 or more).
For example, if we have 1,2,3 searche give us only
1.
If we delete 1, it will be 2 and etc.
Any suggestions?
This is 3 functions
function displayList($clause) {
$clause = ' m.active=1 && g.active=1 && '.$clause;
$pageSize = 12;
$pageNo = isset($_GET['page'])? (int)$_GET['page']:0;
$qr = "SELECT count(DISTINCT m.id) FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause";
$q = $this->execSQL($qr);
list($count) = $q->get();
$pageCount = ceil($count / $pageSize);
if (!$pageCount) $pageCount = 1;
if ($pageCount<=$pageNo) return false;
$offset = $pageNo * $pageSize;
list($sortV, $sort) = $this->getSort();
/*$q = $this->execSQL("SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter, studed, indx, side, remains, price
FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause
ORDER BY $sortV LIMIT $pageSize OFFSET $offset ");*/
$q = "SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter, studed, indx, side, remains, price
FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause GROUP BY m.id
ORDER BY $sortV LIMIT $pageSize OFFSET $offset";
$q = $this->execSQL($q);
$xml = '';
while ($data = $q->getAssoc()) {
$xml.=prop2xml($data);
}
return "<goodslist page='$pageNo' pagesize='$pageSize' pages='$pageCount' sort='$sort'>$xml</goodslist>";
}
function displayBySize() {
$params = $this->kernel->getModul('tyreparams');
$clause = $this->getSQLClause($params);
if ($clause['where'] == '') return '<noparams/>';
$xml = $this->displayList($clause).$params->display();
return "<search>$xml</search>";
}
function getSQLClause($params, $except = array()) {
$cl = array();
foreach($params->params as $id=>$param)
if ($param['value']!='' && !in_array($id, $except)){
$vl = trim($param['value']);
if ('vendor' == $id) {
$cl[] = "m.owner_id IN (SELECT ts.id FROM td_tyres ts WHERE ts.active=1 AND ts.id='$vl')";
}
else {
$pos = strpos($vl, '-');
if ($pos === 0) $pos = strpos($vl, '-', 1);
if ($pos) {
$lo = substr($vl, 0, $pos);
$hi = substr($vl, $pos + 1);
$t = "$id >= '$lo' && $id <= '$hi'";
}
else
$t = "$id = '$vl'";
if ($id == 'PCD') {
$t2 = str_replace('PCD', 'PCD2', $t);
$cl[] = "(($t) || ($t2))";
} else
$cl[] = $t;
}
}
return implode('&&', $cl);
}
UPD
SQL query -
SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter,
studed, indx, side, remains, price FROM td_tyregoods g, td_tyremodels m WHERE m.id =
g.owner_id && m.active=1 && g.active=1 && width = '245'&&profile = '50'&&m.owner_id IN
(SELECT ts.id FROM td_tyres ts WHERE ts.active=1 AND ts.id='13') GROUP BY m.id ORDER BY
name LIMIT 12 OFFSET 0
This query, give in mysql console exactly that we have at the site. Problem in query...

Categories