PHP - Mysql - display data - php

I'm starting to play with PHP and MySQL.
However, I have encountered a problem and can not deal with it.
In my database I have data such as: id, domain_name, year, month, organic_search_visit
I want to display them now using PHP, but the data is displayed not as I want.
The data in my database looks like this:
Site1.com
January - 2017 - 11k visit
February - 2017 - 10k visit
...
January - 2018 - 11k visit
February - 2018 - 10k visit
...
Site2.com
January - 2017 - 11k visit
February - 2017 - 10k visit
...
January - 2018 - 11k visit
February - 2018 - 10k visit
...
I want to display the data from the database using PHP in the table so that it can see how I had traffic in a given year / month.
My code:
$results = $mysqli->query("SELECT domain_name, month, year, organic_search_visit FROM organic_search");
echo "<table>";
echo "<thead><tr>";
while($row = mysqli_fetch_array($results))
{
echo "<td>Month</td>";
echo "<th>".''.$row['month'].''."</th>";
echo "</tr><thead>";
echo "<tr>";
echo "<td>2017</td>";
echo "<td>".''.$row['organic_search_visit'].''."</td>";
}
echo "</tr>";
echo "</table>";

Start with sorted result data. Iterate through the data and print the relevant table and row tags when they change in the data.
You can use something like the example below. Note that this has a fixed list of months for column headers and requires the data to match.
$results = $mysqli->query("SELECT domain_name, month, year, organic_search_visit FROM organic_search GROUP BY domain_name,month,year, ORDER BY domain_name, year, month");
$months = array('January', 'February', 'March'); //etc
$domain = "";
$year = "";
$month = 0;
while($row = mysqli_fetch_array($results))
{
if($domain!=$row['domain_name']){ //Check if the domain has changed
$domain = $row['domain_name'];
$year = "";
$month = 0;
if($domain!="") echo "</tr></table>"; //Only close last domain table if there was a previous domain
echo "<table><tr><th>".$domain."</th>"; //Start new domain table
foreach($months as $month) echo "<td>".$month."</td>"; //Print header row
echo "</tr>";
}
if($year!=$row['year']){
$year = $row['year'];
$month = 0;
if($year!="") echo "</tr>";
echo "<tr><td>".$year."</td>";
}
while($months[$month] != $row['month']){
$month+=1;
echo "<td></td>";
}
echo "<td>".$row['organic_search_visit']."</td>";
}
echo "</tr></table>";

Related

Display the first and last day of a (calendar) week

In my database I have a table with consecutive dates. I group all dates to calendar weeks and display them in a table in my CSS.
Now i want to display also the first and the last day of the calendar week in my table.
Here is my code:
$statement = $pdo->prepare("SELECT WEEK(Date), Date FROM table GROUP BY WEEK(Date)");
$result = $statement->execute();
$count = 1;
while($row = $statement->fetch()) {
echo "<tr>";
echo "<td>".$row['WEEK(Date)']."</td>";
echo "<td>".$row['Date']."</td>";
Currently there is only shown the first day of the calendar week.
I thought of duplicating $row['Date']and adding +6 (days) but the first dataset is not the first day of the week. So the first date range of the first calendar week would be wrong.
Does anyone has an idea how to solve this problem?
See a test of this here: https://www.tehplayground.com/c2dOYxxwIa9LDscW
while($row = $statement->fetch()) {
$thedate = $row['Date'];
$dow = date('w', strtotime($thedate)); // the day of the week of the date - number based - zero is sunday
$dowsun = date('Y-m-d', (strtotime($thedate) - ($dow * 60*60*24))); // first day of that week (sunday)
$dowsat = date('Y-m-d', strtotime($thedate) + ((6-$dow) * 60*60*24)); // last day of that week (saturday)
/* for example:
if $row['WEEK(Date)'] = "2021-06-08" which is a Tuesday
$dowsun = "2021-06-06" which is a Sunday
$dowsat = "2021-06-12" which is a Saturday
with this answer you get the full week that contains the target date
*/
echo "<tr>";
echo "<td>".$row['WEEK(Date)']."</td>";
echo "<td>".$row['Date']."</td>";

Sum hours from time tracker to calendar by day

I've got a working calendar function, and a working sum to calculate the project hours from the time tracker, but I'm struggeling to combine them into a working function.
See comments in code to figure out the current progress, a printscreen is also provided below.
How can I get the QUERY to echo out the SUM based on the $year $month and $day_num on each row in the calendar?
This is my current code:
<?php
include 'db.php';
// GET USER DATA
$sql = "SELECT * FROM users where user_username = '".$_SESSION['username']."'";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$loginuser_id = $_GET['id'];
}
// GET TIME TRACKING DATA
$query = "
SELECT userhours_id, user_hours, hours_timeoccur, SUM(user_hours) as 'myhours' FROM hours h
where h.userhours_id = $loginuser_id
AND h.hours_timeoccur = '2018-09-15'
";
$result = $mysqli->query( $query ) or die($mysqli->error);
$row = $result->fetch_assoc();
$user_hours = $row['myhours'];
// VIEW THE SUM OF HOURS BASED ON THE DAY FROM THE QUERY ABOVE
echo $user_hours;
// THE CALENDAR
showmonth($m = $_GET['m'] ,$y = $_GET['y']);
function showmonth($month, $year) {
$first_day = mktime(0,0,0,$month, 1, $year);
$title = date('F', $first_day);
$day_of_week = date('D', $first_day);
$days_in_month = cal_days_in_month(0, $month, $year);
echo "<div id='container'>";
echo "<div id='datenav'>";
echo "<div id='prevbtn'>prev</div>";
echo "<div id='date'>$title $year</div>";
echo "<div id='nextbtn'>next</div>";
echo "</div>";
echo "<div id='cal'>";
$day_num = 1;
while ( $day_num <= $days_in_month ) {
$cnt = 0;
while ($cnt < 7) {
echo "<div id='days'>";
echo "<h4>$day_num</h4>";
echo "<h5>40h</h5>"; // HERE I WANT THE SUM OF TIME TRACKING BY EACH DAY
echo "</div>";
$day_num++;
if ($day_num > $days_in_month) {break;}
}
}
echo "</div>";
echo "</div>";
} // end of function
?
The current output: (146 is the SUM of all the hours on the specified date in the QUERY, and all the 40h in the picture are manually written. That's the place that I want to echo the QUERY output for each day)
The desired output would be to have 146 on the day it's summarized from listed in the calendar, and the same for each and every other day but with those days hours.
Big thanks in advance and let me know if you need any more data!
Sample data:
DB: hours
hours_id userhours_id projecthours_id user_hours hours_timeoccur
1 5 12377 5 2018-08-14
2 3 12378 100 2018-09-15
3 3 12378 46 2018-09-15
4 1 12378 5 2018-09-16
5 5 12379 5 2018-09-17
DB: users
user_id user_username .....
1 Adam
2 Bryan
3 Clinton
4 David
5 Eric
DB: projects
project_id project_name .....
1 My first test
2 My second test
3 My third test
4 My fourth test
5 My fifth test
Figured it out!
I moved the QUERY inside the calendar code and then it all worked out just perfect!

PHP Calendar displaying list of events

I have a database table that has two columns eventName|eventDate. I have created a function that takes in a startDate and endDate, I want to display the list of events in a ListView with each date as the header.
In my brief example below, I know I can retrieve the full event listings with SQL. How do I then slot the event headers in so that I can return them in a properly formatted array?
function retrieveEvents($startDate, $endDate) {
// run SQL query
//
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// how do I write this part such that I can output event headers in my array
$events = $row;
}
}
}
So my intended output is
1st July 2013 ($startDate)
- Tea with President - 1300h
- Mow the lawn - 1330h
- Shave the cat - 1440h
2nd July 2013
- Shave my head - 0800h
3rd July 2013
4th July 2013 ($endDate)
- Polish the car - 1000h
In your MYSQL query:
SELECT * FROM `yourTableName` WHERE `eventDate` >= $startDate AND `eventDate` <= $endDate
PS: I'm not sure about the quotes arount the variables in your query.
PPS: never use * to select your columns, always only select the columns you need. Here I'm using it because I don't know the names of your columns
I ended up doing my checking in PHP and print a new row only when a different date is detected.
Codes below in case it serves someone's needs in future.
<?php
$currentPrintDay = 0;
$currentPrintMonth = 0;
$currentPrintYear = 0;
echo "<table>"
foreach($reservationsToShow as $row):
// get day, month, year of this entry
$timestamp = strtotime($row['timestamp']);
$day = date('d', $timestamp);
$month = date('m', $timestamp);
$year = date('Y', $timestamp);
// if it does not match the current printing date, assign it to the current printing date,
// assign it, print a new row as the header before continuing
if($day != $currentPrintDay || $month != $currentPrintMonth || $year != $currentPrintYear) {
$currentPrintDay = $day;
$currentPrintMonth = $month;
$currentPrintYear = $year;
echo
"<tr>" .
"<td colspan='100%'>". date('d-m-Y', $timestamp) . "</td>" .
"</tr>";
}
// continue to print event details from here on...
?>

My loop is doubling the results when match is found

I have a database with some months. I am using the following to group similar months:
$Mydates = array();
while(........)
{
$date = $row['date'];
$Mydates[$date] = (isset($Mydates[$date])) ? $Mydates[$date] + 1: 1;
}
My table contains 4 data, 3 Jan's and 1 Feb. Now this information is being run through an array which contains the months of the year. Here is what I have so far:
$months = array("Jan","Feb","Mar",etc........);
foreach($months as $month)
{
foreach($Mydates as $Mydate => $Number)
{
if($month == $Mydate)
{
echo $month." (".$Number.")<br />";
}else{
echo $month."<br />";
}
}
}
Now when there were only Jan's this works fine. Now that I have added another month my results display like below:
Jan(3)
Jan(3)
Feb(1)
Feb(1)
Mar
Mar
etc.....
etc.....
How can I get this to only display once like this:
Jan(3)
Feb(1)
Mar
etc....
Now I have noticed that the more months add the more it duplicates. Can someone look at this and tell me where I am going wrong here?
It seems, $Mydates is already aggregated and accessible by month. Remove the inner loop and just look, if there's a corresponding month in $Mydates
foreach($months as $month) {
if(isset($Mydates[$month])) {
echo $month." (".$Mydates[$month].")<br />";
} else {
echo $month."<br />";
}
}

creating archive for my blog website

my database table is something like :
id year month
1 2011 november
2 2011 november
3 2011 october
i need to create a query so it return something like that :
2011
november
november
october
What is the correct query syntax to do it in php script ?
Here is the code i used :
<?php
$uid = $_SESSION['uid'];
$sql = "SELECT year, GROUP_CONCAT(month) AS months FROM articles GROUP BY year";
$res = mysql_query ($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
while ($rows = mysql_fetch_assoc($res)) {
foreach ($rows AS $row) {
echo $row['year'] . "<br>";
$months = explode(",", $row['months']);
foreach ($months AS $m) {
echo $m . "<br>";
}
}
}
}
?>
You can use GROUP_CONCAT() to return a comma-separated list of months:
SELECT year, GROUP_CONCAT(month) AS months GROM tbl GROUP BY year
Returns:
2011 november,november,october
Or just select both columns and handle the display/presentation in your code:
SELECT year, month FROM tbl WHERE year = 2011
Returns
2011 november
2011 november
2011 october
In code, loop and only display the year when it changes.
Update Since a code example seems warranted...
// Results from above GROUP_CONCAT() query already fetched & stored in `$rowset`:
while ($row = mysql_fetch_assoc($res)) {
$rowset[] = $row;
}
// Now $rowset is a 2D array containing all rows.
foreach ($rowset as $row) {
// Output the year
echo $row['year'] . "\n";
// months are comma-separated via GROUP_CONCAT()
// explode them into an array
$months = explode(",", $row['months']);
foreach ($months as $m) {
// Output the months
echo $m . "\n";
}
}
If I understood your question correctly, I think a simple "ORDER BY" clause would do the trick for you, something similar to:
SELECT * FROM table_name ORDER BY year DESC
Then, use your scripting language to display the data, a good idea could be (maybe) to fetch the year of the first row, store it in a temporal variable, then loop through the rows and check if the year has changed, if it has, change the value of the aforementioned variable, something like this:
$current_year = $data_set[0]['year'];
foreach ( $data_set as $data_row )
{
$current_year = ( $data_row['year'] != $current_year) ? $data_row['year'] : $current_year;
//Do something with it and/or the rest of the data
}
Hope this was of any help.
Cheers.

Categories