PHP Display MYSQL Results within a loop - php

I have a left join, code shown below that takes,
id
referrer
search term
client_id
From table 1 and then takes the following columns from table 2 using the left join query underneath.
client_id
visit_id
timedate
url1
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
echo $row['referrer']. " - ". $row['search_term'];
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}
What I am trying to do is format the rows so the referrer and search term only shows once and not on every line so that the results would look like this.
Referrer Search term
timedate url1 1
timedate Url1 1
timedate url1 1
referrer Search Term
timedate Url1 2
timedate Url1 2
timedate Url1 2
the numbers 1 and 2 are to represent different visit id's by which the results are grouped. At the moment i get the referrer and search term after every row because it is in the loop and understand that. Just don't know if i can show the referrer and searc term just once per group of results.

You have to save the current pending referrer-searchterm combination and check if it changes, if yes, print out the referrer-searchterm line:
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate" .
"ORDER BY referrer, search_term";
$result = mysql_query($query) or die(mysql_error());
$currentReferrerSeatchTerm = null;
while($row = mysql_fetch_array($result)){
$newReferrerSearchTerm = $row['referrer']. " - ". $row['search_term'];
echo '<div id=""><br>';
if($currentReferrerSeatchTerm != $newReferrerSearchTerm){
echo $newReferrerSearchTerm . '<br>';
$currentReferrerSeatchTerm = $newReferrerSearchTerm
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo '<br></div>';
}

I usually set a var to store the referrer then check that on each loop through. If it's the same as the previous, do nothing. If it's different, display the new header info (referrer & search_term in your case) and then update the var.
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
$prevRef = '';
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
if($prevRef != $row['referrer']) {
echo $row['referrer']. " - ". $row['search_term'];
$prevRef = $row['referrer'];
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}

Related

Grabbing info from two different tables, assistance

I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}

Comparing two SQL tables

I am looking to filter results by date, which I gotten to work just fine. Now I'm trying to have the database return values based on each employee in that filtered period. Example in the employee table:
ID Hourly
then in the data table
ID Hours
So I was trying for if the IDs match then look up how much the hourly and hours would total out to. Here's what I have thus far.
<?php
$con=mysqli_connect("MY_INFO.com","USER","*********","DB_NAME");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$data = mysqli_query($con,"Select * FROM employees
Select * FROM data
SELECT t1 *, t2.*
From employees t1
INNER JOIN data t2 on t1.id = t2.id
'");
while($data = mysqli_fetch_array($data)) {
echo $data['id'] . " " . $data['id'];
echo "<br>";
}
$result = mysqli_query($con,"SELECT * FROM friends
WHERE date >'2014-09-1' and date < '2014-9-30'");
while($row = mysqli_fetch_array($result)) {
echo $row['name'] . " " . $row['id'];
echo "<br>";
I'm trying to filter by date, and then match IDs from both tables so if an id equals an id from the other table then it could return an hourly wage. So if employee id: 1 had an hourly wage of $20 / hr and worked 2 hours then I could get it to return $40. The tables would have in them:
Employee:
ID $/hr
1 20
Data:
ID Hours
1 2

Echo data from mysql base to page

I have this query:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
placement.name AS placement,
advertiser.name AS advertiser,
country.name AS country
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
and ads table
ads Table
ad_id PK
size
price
trafficsourceId FK
placementId FK
advertiserId FK
countryId FK
For getting data I'm using
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
}
I cant figure out how I need to print page so that it's not looking like rows but also need id's of for example trafficsource name. I want to make something like that:
EDITED:
<div id="adscontent">
<h1>Advertiser:</h1> Advertiser name
<h2>Traffic Sources:</h2> Company1, Company2, Company 3
<h2>Placements:</h2> Like: Newspaper, radio, website, bla bla
</div>
Thanks
You will need to play around with the printout but I think something like this will work:
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[$row['advertiser']]['countries'][] = $row['country'];
$results[$row['advertiser']]['trafficsources'][] = $row['trafficsource'];
$results[$row['advertiser']]['placements'][] = $row['placement'];
}
// And now print the data
foreach ($results as $arvertiser => $data)
{
echo "<h1>{$advertiser}</h1>";
// Print Placements
echo "Placements: " . implode(", ", $data['placements']) . '<br />;
// Print Countries
echo "Countries: " . implode(", ", $data['countries']) . '<br />;
// Print Placements
echo "Traffic Sources: " . implode(", ", $data['trafficsources']) . '<br />;
}
EDIT: If you need to add the IDs you will need to change your select to:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
trafficsource.id AS trafficsourse_id,
placement.name AS placement,
placement.id AS placement_id,
advertiser.name AS advertiser,
advertiser.id AS advertiser_id,
country.name AS country
country.id AS country_id
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
From then on you can include this information in the $results array like so:
$results[$row['advertiser']['countries'] = array(
'id' => $row['country_id'],
'value' => $row['country')
);
and print out whatever you need from there.

Display all records for mySQL field and count how many times they appear for specific date

My desired result is to display how many times each video (title) was watched for specific dates, by grabbing all of the titles that appear in the table, and count how many times that title is recorded for specific years / months.
It is working, however, it is not displaying correctly.
Instead of
TITLE A - 2
TITLE B - 6
TITLE C - 4
TITLE D - 0
...
It is displaying like this
TITLE A - 2
- 6
- 4
TITLE BTITLECTITLED
my code:
//get report
if ($_GET['report'] == "custom") { //custom date report
$month = $_GET['month'];
$year = $_GET['year'];
$result2 = mysql_query("SELECT DISTINCT title AS displaytitle
FROM user_history GROUP by title");
if ($_GET['month'] == "") {
$result = mysql_query("SELECT title, COUNT(id) FROM user_history
WHERE year(date) = '$year' GROUP BY title");
} else {
$result = mysql_query("SELECT title, COUNT(id) FROM user_history
WHERE year(date) = '$year' AND month(date) = '$month' GROUP BY title");
}
while($row2 = mysql_fetch_array($result2)) {
$new_title = $row2['displaytitle'];
echo $row2['displaytitle'];
while($row = mysql_fetch_array($result)) {
echo ' - ' . $row['COUNT(id)'] . '<br />';
}
}
Can anyone offer a solution so that a count will display next to the title? Thanks!
Your code to display the title is outside the loop. If you want the title to be printed next to every value, put it inside the loop printing every value.
if ($_GET['report'] == "custom") { //custom date report
$sql = "
SELECT
titles.title,
COUNT(DISTINCT history.id) AS `count`
FROM
user_history titles
LEFT OUTER JOIN
user_history history
ON
titles.title = history.title
";
if (!empty($_GET['month']) && !empty($_GET['year'])) {
$sql .= "AND YEAR(history.date) = " . (int)$_GET['year'] . " AND MONTH(history.date) = " . (int)$_GET['month'];
} else if (!empty($_GET['year'])) {
$sql .= "AND YEAR(history.date) = " . (int)$_GET['year'];
}
$sql .= "
GROUP BY
titles.title
ORDER BY
titles.title
";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['title'] . ' - ' . $row['count'] . '<br />';
}
}

LEFT JOIN with SUM not working

hoping I could get a hand with a LEFT JOIN + SUM issue I'm having.
The background: I'm building a wee finance system and want to calculate the value of all invoices within a given month (blank months = null). I have two tables:
tsm_finance_calendar - Containing 'months'.
tsm_finance_invoices - Contains details of each invoice.
My query:
<?php
$query = "SELECT tsm_finance_calendar.month,
SUM(tsm_finance_invoices.totalBilled)
FROM tsm_finance_calendar
LEFT JOIN tsm_finance_invoices
ON tsm_finance_calendar.month = tsm_finance_invoices.month
GROUP BY tsm_finance_calendar.month
ORDER BY 'id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['SUM(totalBilled'];
echo "<br />";
}
?>
Output is on the right track (Month - $Blank) but lacks the result of the sum.
Any help gets a giant high-five :)
Thanks,
RR
Use the as keyword in query
$query = "SELECT tsm_finance_calendar.month, SUM(tsm_finance_invoices.totalBilled) as sum FROM tsm_finance_calendar LEFT JOIN tsm_finance_invoices ON tsm_finance_calendar.month = tsm_finance_invoices.month GROUP BY tsm_finance_calendar.month ORDER BY 'id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['sum'];
echo "<br />";
}
$row["month"]-$row["SUM(totalBilled)"]
and you forgot to close a paren ^
Did u miss a closing parenthesis in 'SUM(totalBilled' there?
echo $row['month']. " - $". $row['SUM(totalBilled'];
And I wonder why you need a JOIN there if both the month field of tsm_finance_invoices is having similar values as tsm_finance_calendar.month ?

Categories