Echo data from mysql base to page - php

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.

Related

select different columns from multiple tables with common variable

I have three tables: - food - toys - animals
Each table has the columns - id, color, item
Table toys has additional columns - sn, date and more
Need to select all items from all tables with color = red and get them separately on client side
Something like:
$color = 'red';
$sql = "select * from food, toys, animals where color = :acolor";
$st = $db->prepare($sql);
$st->execute([":acolor" => $color]);
$food = $toys = $animals = '';
while($row = $st->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
$arr = [];
array_push($arr, $food, $toys, $animals);
echo json_encode($arr);
client side
...
data = JSON.parse(data);
$('#wrapfood').html(data[0]);
$('#wraptoys').html(data[1]);
$('#wrapanimals').html(data[2]);
As the final result:
wrapfood should have 5 divs with class food
wraptoys should have 9 divs with class toys
wrapanimals should have 21 divs with class animals
I tried various versions of the above code without success - getting errors on server side.
Any help?
You can use this
$data = array('food' => array(),'toys' => array(),'animals' => array());
$color = 'red';
$foodSql = "select * from food where color = :acolor";
$toySql = "select * from toys where color = :acolor";
$animalSql = "select * from animals where color = :acolor";
$ft = $db->prepare($foodSql);
$tt = $db->prepare($toySql);
$at = $db->prepare($animalSql);
$ft->execute([":acolor" => $color]);
$tt->execute([":acolor" => $color]);
$at->execute([":acolor" => $color]);
$food, $toys, $animals = '';
while($row = $ft->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
}
array_push($data['food'], $food);
while($row = $tt->fetch()){
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
array_push($data['toys'],$toys);
while($row = $at->fetch()){
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
array_push($data['animals'],$animals);
echo json_encode($data);
Then on client side you can access the data as
data = JSON.parse(data);
$('#wrapfood').html(data.food);
$('#wraptoys').html(data.toys);
$('#wrapanimals').html(data.animals);
if you want to use a single select statement here is the solution... if you just want a color item and id
SELECT f.* from food f
UNION
SELECT a.* from animals a
UNION
SELECT t.id, t.color,t.item from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if you want sn and date also
SELECT f.*,null,null from food f
UNION
SELECT a.*,null,null from animals a
UNION
SELECT t.* from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if your columns of the tales are in the same order as you specified id, color, and item then no problem with the above queries otherwise if the order is different arrange the column names in select statement accordingly...
now you can still use the above query if you want to separate it only client site in the single loop... just concatenate in the select statement.
here is what you can do...
SELECT CONCAT("#food",f.id), CONCAT("#food",f.color),CONCAT("#food",f.item),null,null from food f
UNION
SELECT CONCAT("#animals",a.id),CONCAT("#animals",a.color),CONCAT("#animals",a.item),null,null from animals a
UNION
SELECT CONCAT("#toys",t.id),CONCAT("#toys",t.color),CONCAT("#toys",t.item),CONCAT("#toys",t.sn),CONCAT("#toys",t.date) from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
now we have concatenated the names of the tables with the column now when we display it we can easily filter them with their names...
this is how you filter them later on...
if(substr( $row['id'], 0, 5 ) === "#food"){
echo substr($row['id'],4);
}

Getting data from my join table

I have a join table which takes the id from my respondents table respondant_id and the id from my teams table table_id.
The output is fine when I SELECT from that table so I get back the respondants ID married up with the teams ID.
I am wanting to show the respondents name from respondant_data and the team name from teams by using the values output from the join table.
I have attempted this here but I keep getting 0 results.
$sql = "
SELECT
respondant_data.respondant_id, teams.team_id
FROM
respondant_data
INNER JOIN
teams
ON
respondant_data.respondant_id = teams.team_id
WHERE
respondant_teams.team_id= 5";
$result = $conn->query($sql);
$i = 1;
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $i++ . ' ';
echo 'user_id: ' . $row["respondant_id"] . ', ';
echo 'team_id: ' . $row["team_id"];
echo '<br>';
}
} else{
echo 'no results';
}
So I want my output to be like 'John Smith', 'Central Team'
Try this query.
SELECT
resp_data.respondant_id, teams.team_id
FROM
respondant_data resp_data,
teams,
respondant_teams resp_teams
WHERE
resp_data.respondant_id = teams.team_id
and resp_teams.team_id = teams.team_id
and resp_teams.team_id = 5

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>";
}

PHP - SQL Query filter+

I am working on a php script that will get the required information and display it in an xml. For some reason my brin isn't work and I don't know how to do the query. The database has two tables that I want to pull information from. Both tables have one thing in common which is 'id_member'. Themes table has a bunch of junk in it - so it has 4 coulms - 'id_member', 'id_theme', 'varible', and 'value'. There are two items in 'varible' that I want to filter (show them and not the rest) "cust_armaus" and "cust_armamo" then value will show the value of course. So in the table Themes it will have id_member listed more than once to show the different varibles. This is what I got that isn't working for me:
<?php
header('Content-Type: text/xml');
$username="database_username";
$password="database_password";
$database="database_name";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "<?xml version=\"1.0\"?>\n".
"<!DOCTYPE squad SYSTEM \"squad.dtd\">\n".
"<?xml-stylesheet href=\"squad.xsl?\" type=\"text/xsl\"?>\n";
?>
<squad nick="Team Tag">
<name>Team Name</name>
<email>contact#team.com</email>
<web>http://www.team.com</web>
<picture>teamlogo.paa</picture>
<title>This is the Team motto</title>
<?php
// smf_themes -> id_member =
// smf_themes -> variable for cust_armaus & cust_usermo
// smf_themes -> value <- get for cust_armaus & cust_usermo
// smf_members -> real_name = profile_name & name
// smf_members -> email_address = email - NO
$memberSQL = mysql_query("SELECT id_member AS id, real_name FROM smf_members");
$member = mysql_fetch_array($memberSQL);
$armausSQL = mysql_query("SELECT id_member, variable, value AS arma_id FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_armaus'");
$armaid = mysql_fetch_array($armausSQL);
$armamoSQL = mysql_query("SELECT id_member, variable, value AS motto FROM smf_themes WHERE id_member='$member[id]' AND variable='cust_usermo'");
$armamo = mysql_fetch_array($armamoSQL);
$num=mysql_numrows($member, $armaid, $armamo);
mysql_close();
$i=0;
while ($i < $num) {
$profile_id = mysql_result($armaid,$i,"value");
$profile_name = mysql_result($member,$i,"real_name");
$profile_remark = mysql_result($armamo,$i,"value");
$profile_username = mysql_result($member,$i,"real_name");
//$profile_email = mysql_result($result,$i,"email");
//$profile_icq = mysql_result($result,$i,"icq");
echo "<member id=\"$profile_id\" nick=\"$profile_name\">" .
"<name>$profile_name</name>".
"<email>$profile_email</email>".
"<icq>$profile_icq</icq>".
"<remark>$profile_remark</remark>".
"</member>\n";
$i++;
}
?>
</squad>
The mysql interface is deprecated. New development should use either mysqli or PDO.
Assuming you only one one value of the cust_armaus and cust_usermo rows for each smf_members, you could use correlated subqueries in the SELECT list, and return just a single query that returns a single row for each row in smf_members. Something like this:
SELECT m.id_member AS id
, m.real_name
, (SELECT a.value
FROM smf_themes a
WHERE a.id_member = m.id_member
AND a.variable = 'cust_armaus'
ORDER BY a.value LIMIT 1
) AS cust_armaus
, (SELECT u.value
FROM smf_themes u
WHERE u.id_member = m.id_member
AND u.variable = 'cust_usermo'
ORDER BY u.value LIMIT 1
) AS cust_usermo
FROM smf_members m
ORDER BY m.id_member
If the (id_member,variable) tuple is guaranteed to be unique in smf_themes, you could use a simpler outer join:
SELECT m.id_member AS id
, m.real_name
, a.value AS cust_armaus
, u.value AS cust_usermo
FROM smf_members m
LEFT
JOIN smf_themes a
ON a.member_id = m.member_id AND a.variable = 'cust_aramus'
LEFT
JOIN smf_themes u
ON u.member_id = m.member_id AND u.variable = 'cust_usermo'
ORDER BY m.id_member
With either of those queries, you could use code something like this:
$sql = "SELECT ...";
$rs = $mysqli->query($sql)
if (!$rs) {
// handle error
echo 'query failed: (' . $mysqli->errno . ') ' . $mysqli->error;
die;
}
// loop through rows returned
while ( $row = $rs->fetch_assoc() ) {
echo '<member id="' . htmlspecialchars($row['id']) . '"'
. ' nick="' . htmlspecialchars($row['real_name']) . '">'
. '<cust_aramus>' . htmlspecialchars($row['cust_aramus']) . '</cust_aramus>'
. '<cust_usermo>' . htmlspecialchars($row['cust_usermo']) . '</cust_usermo>' ;
}

PHP displaying data from four tables in one query (ie: LEFT JOIN)

I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));

Categories