temporary table and foreach - php

$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'];
}

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']

SQL Server query returning no results in PHP, but runs fine in Management Studio

I have a rather large query that works fine in Microsoft SQL Server Management Studio. However when I try to run the same query in PHP, I'm getting no results. Here is my code, I know this is the worst way to connect to the database.
Public function GetClockedHours() {
$conn = odbc_connect('easydo', '', '');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "WITH ByDays AS ( -- Number the entry register in each day
SELECT
EventTm AS T,
CONVERT(VARCHAR(10),EventTm,102) AS Day,
FLOOR(CONVERT(FLOAT,EventTm)) DayNumber,
ROW_NUMBER() OVER(PARTITION BY FLOOR(CONVERT(FLOAT,EventTm)) ORDER BY EventTm) InDay
FROM CHINA_VISION_DorEvents
Where DorCtrls_Ref = '16' AND CardCode = '000006f1' AND CONVERT(Date,EventTm) > dateadd(day, -7, getdate())
)
,Diffs AS (
SELECT
E.Day,
E.T ET, O.T OT, O.T-E.T Diff,
DATEDIFF(S,E.T,O.T) DiffSeconds -- difference in seconds
FROM
(SELECT BE.T, BE.Day, BE.InDay
FROM ByDays BE
WHERE BE.InDay % 2 = 1) E -- Even rows
INNER JOIN
(SELECT BO.T, BO.Day, BO.InDay
FROM ByDays BO
WHERE BO.InDay % 2 = 0) O -- Odd rows
ON E.InDay + 1 = O.InDay -- Join rows (1,2), (3,4) and so on
AND E.Day = O.Day -- in the same day
)
SELECT Day,
SUM(DiffSeconds) Seconds,
CONVERT(VARCHAR(8),
(DATEADD(S, SUM(DiffSeconds), '1900-01-01T00:00:00')),
108) TotalHHMMSS -- The same, formatted as HH:MM:SS
FROM Diffs GROUP BY Day
ORDER BY Day desc";
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
$array = array();
$i = 1;
while ($row = odbc_fetch_array($rs, $i)) {
foreach ($row AS $key => $value) {
$array[$i][$key] = $row[$key];
}
$i++;
}
var_dump($array);
return $array;
}
The expected result would be an array of results and the results would be:
Date Seconds hours
2015.01.27 18055 05:00:55
2015.01.26 33491 09:18:11
2015.01.23 32649 09:04:09
2015.01.22 31554 08:45:54
2015.01.21 31889 08:51:29
However what were are getting is an array of nothing.
How many results sets do you get back? If it's more than 1 then you need to pick the correct resultset:
bool odbc_next_result ( resource $result_id )
http://php.net/manual/en/function.odbc-next-result.php
I had this same problem. In my case I was executing like this
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
while ($data = odbc_fetch_array($resultSet)) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);//failed here
while ($data2 = odbc_fetch_array($resultSet2)) {
//something here
}
}
and I changed like this and it worked
$sql = "SELECT * FROM table1";
$resultSet = odbc_exec($sqllink, $sql);
// Create an array and store the results
$queryResult = array();
while ($data = odbc_fetch_array($resultSet)) {
// push the required content into the array
$queryResult[$data['id']]['name'] = $data[name];
}
foreach($queryResult as $row) {
$sql = "SELECT * FROM table2";
$resultSet2 = odbc_exec($sqllink, $sql);
while ($data2 = odbc_fetch_array($resultSet2)) {
// something here
}
}

mysql_fetch_array only running once, should be six

I can see in my logcat that the $check query is only running once, when it should be running once for every result of the $result query, which is 6. I've been troubleshooting this for hours and I just can't figure out why it's not working properly.
Is there an obvious reason why $check is only running once?
$result = mysql_query("SELECT * FROM `posts` WHERE facebook_id = $fbid ORDER BY id DESC") or die(mysql_error());
while ($row1 = mysql_fetch_array($result))
{
$mytime = $row1['time'];
$mylat = $row1['latitude'];
$mylon = $row1['longitude'];
$mypostid = $row1['id'];
// get all products from products table
$check = mysql_query("SELECT facebook_id as fid, id as uid,
TIMESTAMPDIFF(SECOND, `time`, '$mytime') AS timediff
FROM `posts`
WHERE `facebook_id` != $fbid
HAVING `timediff` <= '180'
ORDER BY `time` DESC") or die(mysql_error());
if (mysql_num_rows($check) > 0)
{
$response["products"] = array();
while ($row = mysql_fetch_array($check))
{
// temp user array
$product = array();
$product["facebookid"] = $row["fid"];
$product["timediff"] = $row["timediff"];
$product["theirpostid"] = $row["uid"];
$product["mypostid"] = $mypostid;
// push single product into final response array
array_push($response["products"], $product);
}
}
}
$response["success"] = 1;
echo json_encode($response);
I guess this is because you set
$response["products"] = array();
inside every cycle. Move it out of this inner while.

PHP Optimizing a check

I'm trying to optimize this check I have. I need to check table called lines and see if any row has matching Earned and Maxearned values (only rows with Position 1,2,3,4). If they do, I need to grab Earned from that row, write it in a different table called bank and remove that row from table called lines. This is what I have:
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
foreach ($users as $user)
{
$sql6 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
$result4 = mysql_query($sql6);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
}
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql4 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('$user','$earned','$method','$today','$type','$status')";
$sql5 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
}
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
}
I'm trying to avoid having to run a different query ($sql6 and the while after that) to grab the value of Earned column. Is there a way to do this? I've tried everything and this is pretty much the best I came up with.
You can do something like this:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
$users_to_compare = "(" . rtrim(implode(",", $users),',') . ")";
$sql4 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result4 = mysql_query($sql4);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql5 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('{$row4['User']}','$earned','$method','$today','$type','$status')";
$result5 = mysql_query($sql5);
}
$sql6 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result6 = mysql_query($sql6);
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
$result7 = mysql_query($sql7);
if ($result5 && $result5 && $result7) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
}
Going one step further you can also use Batch INSERT for you insert queries
Note: Dont forget that mysql_* versions are depreceated you should use mysqli_*

What is wrong with this code?

Why is it that when I view the month of November 2010 it also views the month of 2009? Can anyone help me?
<?php include("db.php");
$query = mysql_query("SELECT distinct YEAR(local_date) as year FROM tbl_localnews order by local_date desc");
while ($row = mysql_fetch_array($query)) {
//$row = array_unique($r);
$unique_year = $row['year'];
echo($unique_year)."<br>";
$query2 = mysql_query("select distinct monthname(local_date) as month from tbl_localnews where local_date like '$unique_year%' order by local_date desc");
while ($r2 = mysql_fetch_array($query2)) {
//$row2 = array_unique($r2);
$unique_month = $r2['month'];
print("<a href='news.php?month=$unique_month'&year=$unique_year>News for $unique_month</a><br>");
//echo($unique_month);
}
}
?>
This is my display
<?php
$year = $_REQUEST['year'];
$last_date = "";
$result = mysql_query("SELECT *,YEAR(local_date) as year FROM tbl_localnews where year(local_date)='".$year."' ORDER BY local_date DESC ");
//echo '<h1>'.$month.'</h1>';
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result)) {
if ($row['local_date'] != $last_date) {
print("<h2>News for ".date('F j, Y', strtotime($row['local_date']))."</h2>");
$last_date = $row['local_date'];
}
print("<p><b>".$row['local_title']."</b></p>");
print("<p>".$row['local_desc']."</p>");
// print("<p><b>".date('F j, Y',strtotime($row['local_date']))."</b></p>");
//print("<p><b>".$row['local_title']."</b></p>");
//print("<p>".$row['local_desc']."</p>");
}
mysql_free_result($result);
}
?>
I take it that you're seeing something like
2010<br><a href='news.php?month=November&year=2010'>News for November</a><br>
2009<br><a href='news.php?month=September&year=2009'>News for September</a><br>
in the output of your first example? This is because you're looping through each year and for each year, you're retrieving the months:
$query = mysql_query("SELECT distinct YEAR(local_date) as year FROM tbl_localnews order by local_date desc");
while($row = mysql_fetch_array($query)) { // loop through each year
$unique_year = $row['year'];
echo($unique_year)."<br>";
/* get the months for current year */
$query2 = mysql_query("select distinct monthname(local_date) as month from tbl_localnews where local_date like '$unique_year%' order by local_date desc");
while($r2 = mysql_fetch_array($query2)) { // loop through each month for the current year
$unique_month = $r2['month'];
print("<a href='news.php?month=$unique_month'&year=$unique_year>News for $unique_month</a><br>");
}
}
if you have 2 records with unique year values in your tbl_localnews table you're going to end up with 2 lines in your output. If you just want 1 record, append LIMIT 1 to the end of your query.
I managed to get the following to work for your display page:
<?php
include("db.php");
$year = $_REQUEST['year'];
$month = $_REQUEST['month'];
$last_date = "";
$result = mysql_query("SELECT *, YEAR(local_date) as year FROM tbl_localnews where YEAR(local_date)=".$year." AND monthname(local_date) = '".$month."' ORDER BY local_date DESC ");
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_array($result)) {
if ($row['local_date'] != $last_date) {
print("<h2>News for ".date('F j, Y', strtotime($row['local_date']))."</h2>");
$last_date = $row['local_date'];
}
print("<p><b>".$row['local_title']."</b></p>");
print("<p>".$row['local_desc']."</p>");
}
}
mysql_free_result($result);
?>

Categories