MySQL query with one variable - php

I have a table called 'main_table' with 3 columns :
'player', 'points' and 'drop_date'
I have 1 variable ($date) with different values:
$date == '2012-06-01'
$date == '2012-05-01'
$date == '2012-04-01'
I Have 1 MySQL query:
$query = "
select *
from main_table
where `drop_date` > '$date'
AND `drop_date` <= DATE_ADD('$date', INTERVAL 1 YEAR)
LIMIT 1
";
GOAL :
I would like to run ONE query with different passes (1pass per value)
I have tried :
<?php
$date['date'] = '2012-06-01';
$date['date'] = '2012-05-01';
$date['date'] = '2012-04-01';
foreach($date as $title => $actual_date) {
query = "
select *
from main_table
where `drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
LIMIT 1
";
$result = mysql_query($query) or die(mysql_error());
}
while($row = mysql_fetch_array($result)) {
echo $row['Player'];
echo $row['Points'];
}

You keep overwriting the same variable over and over... and then you run the query but only fetch results for the last one. How do you expect it to work?
Try this:
$date = Array("2012-06-01","2012-05-01","2012-04-02");
foreach($date as $actual_date) {
if( $result = mysql_fetch_assoc(mysql_query("select * from `main_table` where `drop_date`>'".$actual_date."' and `drop_date`<=date_add('".$actual_date."',interval 1 year) limit 1"))) {
echo $result['Player'];
echo $result['Points'];
}
}
Note that I skipped putting the query in a variable, and putting the query result in a variable, and just one-lined the whole thing. Since you have limit 1 the query will only return one row, so there is no need to while-loop it.

Just move your while in the foreach loop.
<?php
$date[0] = '2012-06-01';
$date[1] = '2012-05-01';
$date[2] = '2012-04-01';
foreach($date as $title => $actual_date)
{
query = "select * from main_table where `drop_date` > '$actual_date' AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR) LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Player'];
echo $row['Points'];
}
}

Do not overwrite your values. Do this to keep all 3 values.
<?php
$date['date'][] = '2012-06-01';
$date['date'][] = '2012-05-01';
$date['date'][] = '2012-04-01';
print_r($date);
?>
OUTPUT:
Array
(
[date] => Array
(
[0] => 2012-06-01
[1] => 2012-05-01
[2] => 2012-04-01
)
)
Then use
foreach ($date['date'] as $actual_date) {
$query = "
select *
from main_table
where `drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
LIMIT 1";
echo $query."<br />";
}
OUTPUT:
select *
from main_table
where `drop_date` > '2012-06-01'
AND `drop_date` <= DATE_ADD('2012-06-01', INTERVAL 1 YEAR)
LIMIT 1
<br />
select *
from main_table
where `drop_date` > '2012-05-01'
AND `drop_date` <= DATE_ADD('2012-05-01', INTERVAL 1 YEAR)
LIMIT 1
<br />
select *
from main_table
where `drop_date` > '2012-04-01'
AND `drop_date` <= DATE_ADD('2012-04-01', INTERVAL 1 YEAR)
LIMIT 1
<br />

Related

How to save the count() group by from mysql into a php variable

I need to save the count(activity_type) group by user_posted_to into a variable from mysql query
$query = "
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user_posted_to = (int)$row['user_posted_to'];
$timestamp = time();
// I need to insert the count into this table for number_assert
$query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if($confirm_query2) {
echo "success query 2";
} else {
echo "failed query 2";
}
}
i expect to save the count() group by into a php variable and to be able to use it later on the page
You want to alias the « COUNT(*) » to something else, like « cnt ». Then you can access the column by name after fetching, as demonstrated below :
$query = "
SELECT
user_posted_to,
COUNT(*) as cnt
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like'
AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
AND activity_type <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY activity_timestamp DESC
LIMIT 25";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
}
} else {
echo "0 results";
}
Add and AS label to the COUNT(*) then you will be able to readout that label in the row you get.
$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";
$nummerOfCount = $row['varCount']

Get info from mysql by date

I have a script written in PHP which reports sales activity.
FOLLOWING currently fetching just values. Today Yesterday Last 7 days.
Today for field use the following code:
if($x==0) {
$sql="SELECT SUM(incasat) FROM tichete WHERE DATE(datainchis) = DATE(NOW()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
Field yesterday to use the following code:
if($x==1) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
I would like to do like this. I wish I could show collections on each and every day like Today Yesterday 3 days ago 3 days but for 3 days ago i want to see like yesterday not amount just pays from this day.
Enclose the code.
function get_user_incasari($x,$y)
{ // 0 - azi, 1 - ieri, 7 - ultimele 7 zile, 30 - luna asta, 31 - luna trecuta
if($x==0) {
$sql="SELECT SUM(incasat) FROM tichete WHERE DATE(datainchis) = DATE(NOW()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==1) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==3) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -3 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==7) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -7 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==30) { //luna curenta
$sql="SELECT SUM(incasat) FROM tichete WHERE MONTH(datainchis) = MONTH(CURDATE()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==31) { //luna precedenta/trecuta
$sql="SELECT SUM(incasat) FROM tichete WHERE MONTH(datainchis) = MONTH(CURDATE() - INTERVAL 1 MONTH ) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
}
You can use timestamps (like your datainchis column), truncated to date, in GROUP BY queries. It's easy. For example, this gives you a summary, by day, starting eight days ago and ending yesterday. (Note: CURDATE() means DATE(NOW()).)
SELECT SUM(incasat) incasat_total, DATE(datainchis) datainchis
FROM tichete
WHERE inchisde='$y'
AND datainchis >= CURDATE() - INTERVAL 8 DAY
AND datainchis < CURDATE()
GROUP BY DATE(datainchis) WITH ROLLUP
Notice, please, that your code contains an error (a common error).
If you have timestamps and you say
datainichis BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE()
you get all the rows with timestamps starting with midnight yesterday, up to and including midnight today. You actually want to exclude midnight today; those records belong to today, not yesterday.
datainichis >= CURDATE() - INTERVAL 1 DAY
AND datainichis < CURDATE()
Notice the < in place of <=.
Your code also contains an inefficiency. The expression
DATE(datainichis) = CURDATE()
is not sargable. It defeats the use of an index on the datainichis column.
I have written a little essay on this topic, here.

How to combine two results?

How can I display results from these two queries in same row. Something like a 17/8 (Kills/Deaths).
I have two queries, first:
$result1 = mysql_query("SELECT PlayerTable.Player AS 'Player', COUNT(CASE WHEN PlayerTable.InitiatorGroupCat = 'AIRPLANE' THEN PlayerTable.InitiatorGroupCat END) AS Airplane
FROM
(
SELECT HitTbl.InitiatorPlayer AS 'Player', DeadTbl.InitiatorGroupCat
FROM
(
SELECT *
FROM stats
WHERE (EVENT = 'S_EVENT_PILOT_DEAD')
AND InitiatorGroupCat != ''
) AS DeadTbl
JOIN
(
SELECT *
FROM stats
WHERE EVENT = 'S_EVENT_HIT'
) AS HitTbl
ON DeadTbl.InitiatorID = HitTbl.TargetID
WHERE HitTbl.Time IN
(
SELECT MAX(TIME)
FROM stats
WHERE EVENT = 'S_EVENT_HIT'
GROUP BY TargetID
)
GROUP BY DeadTbl.InitiatorID,DeadTbl.Time
ORDER BY DeadTbl.Time ASC
) AS PlayerTable
GROUP BY PlayerTable.Player
ORDER BY Airplane DESC
");
//return the array and loop through each row
$i = 1;
while ($row2 = mysql_fetch_assoc($result1))
{
?>
<tr valign="top">
<td align=center><?php echo $i ++; ?>.</td>
<td> <?php echo $row2['Player'];?></td>
<td align=center><?php echo $row2['Airplane'];?></td>
</tr>
Second query:
$result2 = mysql_query("SELECT InitiatorPlayer, COUNT(CASE WHEN InitiatorGroupCat = 'AIRPLANE' THEN InitiatorGroupCat END) AS Deaths
FROM stats
WHERE (EVENT = 'S_EVENT_DEAD' OR EVENT = 'S_EVENT_PILOT_DEAD' OR EVENT = 'S_EVENT_EJECTION')
AND InitiatorGroupCat != ''
GROUP BY InitiatorPlayer
ORDER BY Airplane DESC");
Both queries work but I need result from second query display in row from first in form:
1.| Player | 17/8 (8 is result from second query)
This is the combination (new column in first query divided by "/"):
<?php echo $row2['Airplane']. " / ".$row2['Deaths'];?>
Solved in this way:
<?php
$result1 = mysql_query("SELECT PlayerTable.Player AS 'Player', COUNT(CASE WHEN PlayerTable.InitiatorGroupCat = 'AIRPLANE' THEN PlayerTable.InitiatorGroupCat END) AS Airplane
FROM
(
SELECT HitTbl.InitiatorPlayer AS 'Player', DeadTbl.InitiatorGroupCat
FROM
(
SELECT *
FROM stats
WHERE (EVENT = 'S_EVENT_PILOT_DEAD' OR EVENT = 'S_EVENT_DEAD' )
AND InitiatorGroupCat != ''
) AS DeadTbl
JOIN
(
SELECT *
FROM stats
WHERE EVENT = 'S_EVENT_HIT'
) AS HitTbl
ON DeadTbl.InitiatorID = HitTbl.TargetID
WHERE HitTbl.Time IN
(
SELECT MAX(TIME)
FROM stats
WHERE EVENT = 'S_EVENT_HIT'
GROUP BY TargetID
)
GROUP BY DeadTbl.InitiatorID,DeadTbl.Time
ORDER BY DeadTbl.Time ASC
) AS PlayerTable
GROUP BY PlayerTable.Player
ORDER BY Airplane DESC
");
$result2 = mysql_query("SELECT InitiatorPlayer, COUNT(CASE WHEN InitiatorGroupCat = 'AIRPLANE' THEN InitiatorGroupCat END) AS Deaths
FROM stats
WHERE (EVENT = 'S_EVENT_PILOT_DEAD' OR EVENT = 'S_EVENT_DEAD')
AND InitiatorGroupCat != ''
GROUP BY InitiatorPlayer");
//return the array and loop through each row
//return the array and loop through each row
$i = 1;
while (($row2 = mysql_fetch_array($result1)) && ($row1 = mysql_fetch_array($result2)))
{
?>
<tr valign="top">
<td align=center><?php echo $i ++; ?>.</td>
<td> <?php echo $row2['Player'];?></td>
<td align=center><?php echo $row2['Airplane']. " / " .$row1['Deaths'];?></td>
</tr>
This is a key:
while (($row2 = mysql_fetch_array($result1)) && ($row1 = mysql_fetch_array($result2)))

How can I write this multiple-count loop as a single query?

I'm really stumped here, I've tried using:
sum(case when date_format(from_unixtime(l.date_updated), '%Y-%m-%d') = date_format(now(), '%Y-%m-%d') then 1 else 0 end) AS day0_leads,
in my query, and it did not work as intended, so I ended up using this:
<?php
$total_days = '14';
for ($i = $total_days - 1; $i >= 0; $i--)
{
$day = strtotime('-'.$i.' days');
$day_string = date('n/j', $day);
$leads = mysql_result(mysql_query("select count(*) from `leads` where date_format(from_unixtime(`date_updated`), '%m-%d-%Y') = date_format(from_unixtime($day), '%m-%d-%Y')"), 0);
$assigns = mysql_result(mysql_query("select count(*) from `assigns` where date_format(from_unixtime(`date_assigned`), '%m-%d-%Y') = date_format(from_unixtime($day), '%m-%d-%Y') and `id_dealer` not in (1,2,3)"), 0);
echo "['$day_string', $leads, $assigns]";
if ($i > 0)
echo ',';
}
?>
It is making the page load slow, obviously due to unnecessary queries. What is the proper way of writing this as a single query and outputting the results? Like I said, I've tried a sum with a then else, and it did not product the correct numbers.
Any help would greatly be appreciated.
Heres my solution:
$total_days = '14';
// get leads count array
$sql = mysql_query("select count(*) as `count`, `date_updated`
from `leads`
where date_format(from_unixtime(`date_updated`), '%Y-%m-%d') >= date_format(now() - interval $total_days day, '%Y-%m-%d')
group by date(from_unixtime(`date_updated`));") or die(mysql_error());
$leads_count = array();
while ($row = mysql_fetch_assoc($sql))
$leads_count[date('n/j', $row['date_updated'])] = $row['count'];
// get assigns count array
$sql = mysql_query("select count(*) as `count`, `date_assigned`
from `assigns`
where date_format(from_unixtime(`date_assigned`), '%Y-%m-%d') >= date_format(now() - interval $total_days day, '%Y-%m-%d') and `id_dealer` not in (1,2,3,4)
group by date(from_unixtime(`date_assigned`));") or die(mysql_error());
$assigns_count = array();
while ($row = mysql_fetch_assoc($sql))
$assigns_count[date('n/j', $row['date_assigned'])] = $row['count'];
for ($i = $total_days - 1; $i >= 0; $i--)
{
$day = strtotime('-'.$i.' days');
$day_string = date('n/j', $day);
$leads = ((empty($leads_count[$day_string])) ? '0' : $leads_count[$day_string]);
$assigns = ((empty($assigns_count[$day_string])) ? '0' : $assigns_count[$day_string]);
echo "['$day_string', $leads, $assigns]";
if ($i > 0)
echo ',';
}

temporary table and foreach

$date['"01.06.2012"'] = '2012-06-01';
$date['"01.05.2012"'] = '2012-05-01';
$date['"01.04.2012"'] = '2012-04-01';
$date['"01.03.2012"'] = '2012-03-01';
$date['"01.02.2012"'] = '2012-02-01';
$date['"01.01.2012"'] = '2012-01-01';
foreach($date as $month => $actual_date)
{ /* start foreach loop */
$query = "select Player, SUM(points) AS score from rankings WHERE
`drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
GROUP BY Player
ORDER BY SUM(sa_points) LIMIT 0,5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['player'];
echo $row['score']; }
} /* end foreach loop */
Now I just want add another query to this resulting table, I have tried create temporary table but didnt know where to put it according to the foreach loop and kept getting either parse errors or last $actual_date results.
Is this what you are trying to reach?
$date['"01.06.2012"'] = '2012-06-01';
$date['"01.05.2012"'] = '2012-05-01';
$date['"01.04.2012"'] = '2012-04-01';
$date['"01.03.2012"'] = '2012-03-01';
$date['"01.02.2012"'] = '2012-02-01';
$date['"01.01.2012"'] = '2012-01-01';
mysql_query('CREATE TEMPORARY TABLE results (player varchar(100), score int)');
foreach($date as $month => $actual_date)
{ /* start foreach loop */
$query = "insert into results (player, score)
select Player, SUM(points) AS score from rankings WHERE
`drop_date` > '$actual_date'
AND `drop_date` <= DATE_ADD('$actual_date', INTERVAL 1 YEAR)
GROUP BY Player
ORDER BY SUM(sa_points) LIMIT 0,5";
mysql_query($query) or die(mysql_error());
} /* end foreach loop */
$result = mysql_query('select * from results') or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['player'];
echo $row['score'];
}

Categories