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)
Related
i had a problem in php install.php file
Cannot use object of type MysqlResultSet
i dont know why is my code not working
and this is my code
$this->provider->executeQuery('INSERT INTO perfect SET type="kings", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players['name'], $get_players['email'], 0, date('Y.m.d'))
);
any idea ?
full code is
public function _isperfect()
{
// attackers
$count_attackers = 0;
$attackers_points = 0;
$attackers = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='attackers' ORDER BY points DESC LIMIT 3");
while ( $attackers->next( ) )
{
$attackers_points = $attackers->row['points'];
$count_attackers++;
}
if($count_attackers < 3)
{
$attackers_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, attack_points FROM p_players WHERE attack_points > %s', array($attackers_points));
while ( $get_players->next( ) )
{
$get_att = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='attackers' && email='". $get_players->row['email'] ."'");
if($get_att != NULL && $get_att['points'] < $get_players->row['attack_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="attackers" && email="'. $get_players->row['email'] .'"');
}
if($get_att['points'] < $get_players->row['attack_points'] || $get_att == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="attackers", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['attack_points'], date('Y.m.d'))
);
}
}
$att = 0;
$attack = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='attackers' ORDER BY points DESC LIMIT 3");
while ( $attack->next( ) )
{
$att = $attack->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="attackers"', array($att));
// end attackers
// defenders
$count_defenders = 0;
$defenders_points = 0;
$defenders = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='defenders' ORDER BY points DESC LIMIT 3");
while ( $defenders->next( ) )
{
$defenders_points = $defenders->row['points'];
$defenders_points++;
}
if($count_defenders < 3)
{
$defenders_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, defense_points FROM p_players WHERE defense_points > %s', array($defenders_points));
while ( $get_players->next( ) )
{
$get_def = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='defenders' && email='". $get_players->row['email'] ."'");
if($get_def != NULL && $get_def['points'] < $get_players->row['defense_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="defenders" && email="'. $get_players->row['email'] .'"');
}
if($get_def['points'] < $get_players->row['defense_points'] || $get_def == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="defenders", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['defense_points'], date('Y.m.d'))
);
}
}
$def = 0;
$defend = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='defenders' ORDER BY points DESC LIMIT 3");
while ( $defend->next( ) )
{
$def = $defend->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="defenders"', array($def));
// end defenders
// empires
$count_empires = 0;
$empires_points = 0;
$empires = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='empires' ORDER BY points DESC LIMIT 3");
while ( $empires->next( ) )
{
$empires_points = $empires->row['points'];
$count_empires++;
}
if($count_empires < 3)
{
$empires_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, total_people_count FROM p_players WHERE total_people_count > %s', array($empires_points));
while ( $get_players->next( ) )
{
$get_emp = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='empires' && email='". $get_players->row['email'] ."'");
if($get_emp != NULL && $get_emp['points'] < $get_players->row['total_people_count'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="empires" && email="'. $get_players->row['email'] .'"');
}
if($get_emp['points'] < $get_players->row['total_people_count'] || $get_emp == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="empires", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['total_people_count'], date('Y.m.d'))
);
}
}
$emp = 0;
$empir = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='empires' ORDER BY points DESC LIMIT 3");
while ( $empir->next( ) )
{
$emp = $empir->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="empires"', array($emp));
// end empires
// looters
$count_looters = 0;
$looters_points = 0;
$looters = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='looters' ORDER BY points DESC LIMIT 3");
while ( $looters->next( ) )
{
$looters_points = $looters->row['points'];
$count_looters++;
}
if($count_looters < 3)
{
$looters_points = 0;
}
$get_players = $this->provider->fetchResultSet('SELECT name, email, thief_points FROM p_players WHERE thief_points > %s', array($looters_points));
while ( $get_players->next( ) )
{
$get_loo = $this->provider->fetchRow("SELECT points FROM perfect WHERE type='looters' && email='". $get_players->row['email'] ."'");
if($get_loo != NULL && $get_loo['points'] < $get_players->row['thief_points'])
{
$this->provider->executeQuery('DELETE FROM perfect WHERE type="looters" && email="'. $get_players->row['email'] .'"');
}
if($get_loo['points'] < $get_players->row['thief_points'] || $get_loo == null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="looters", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players->row['name'], $get_players->row['email'], $get_players->row['thief_points'], date('Y.m.d'))
);
}
}
$loo = 0;
$loote = $this->provider->fetchResultSet( "SELECT points FROM perfect WHERE type='looters' ORDER BY points DESC LIMIT 3");
while ( $loote->next( ) )
{
$loo = $loote->row['points'];
}
$this->provider->executeQuery('DELETE FROM perfect WHERE points < %s && type="looters"', array($loo));
// end looters
// kings
$end_server = $this->provider->fetchRow( "SELECT win_pid, game_over FROM `g_settings`");
$end_server_player = $this->provider->fetchRow( 'SELECT `name`,`email` FROM `p_players` WHERE id='.$end_server['win_pid'].' ');
if($end_server_player != null)
{
$this->provider->executeQuery('INSERT INTO perfect SET type="kings", name="%s", email="%s", points="%s", p_date="%s"',
array($get_players['name'], $get_players['email'], 0, date('Y.m.d'))
);
}
}
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%'")
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();
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...
My SQL query is based on data provided.
For example :
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array( 'column1', 'column2', 'column3' );
// query
$select = $table->select();
$select->where('deleted = ?', '0' );
for( $i = 0; $i < count( $columns ); $i++ ) {
if( $i == 0 ) {
$select->where( $columns[$i] . ' > ?', '0' );
} else {
$select->orWhere( $columns[$i] . ' > ?', '0' );
}
}
$select->where('disabled = ?', '0' );
// print query
echo $select->assemble();die();
Above code result into following query:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND
(disabled = '0')
But I want something like this:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0' OR column2 > '0' OR column3 > '0') AND
(disabled = '0')
How it is possible ?
Thanks
I think this should do the job:
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array('column1', 'column2', 'column3');
// query
$select = $table->select();
$select->where('deleted = ?', '0');
$myOrParts = array();
for ($i = 0; $i < count($columns); $i++) {
$myOrParts []= $table->getAdapter()->quoteInto($columns[$i] . ' > ?', '0');
}
$myWhere = implode(' OR ', $myOrParts);
$select->where(new Zend_Db_Expr($myWhere));
$select->where('disabled = ?', '0');
// print query
echo $select->assemble();
die();