select different columns from multiple tables with common variable - php

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

Related

single instead of double select statement

first table - bplus - has a column named home01 with values identical to some values in column fname of table banners
$items = '';
$sql = "select home01 from bplus";
$st = $db->query($sql);
$arr = $st->fetchAll(PDO::FETCH_COLUMN);
foreach ($arr as $el){
$el = trim($el);
$sqlb = "select * from banners where fname = '" . $el . "'";
$stb = $db->query($sqlb);
$row = $stb->fetch();
$items .= "<img class='itemtop' src = '../banners/" . $el . "' alt='img' data-id = " . $row['id'] . " data-fname = '" . $row['fname'] . ">\n";
}
echo $items;
this works but probably there is a shorter way, with a single select statement.
Any help?
use LEFT JOIN
select bplus.home01, banners.* from bplus left join banners on bplus.home01 = banners.fname;

PHP MySQL - foreach loop with if to display subset list within key list

I am trying to display records of venues, with a listing of rooms within each unique record. I have two tables, a venue_lookup table and a venue_lookup_room table. using the slow example I am struggling to ONLY populate each venue with the rooms that are contained within. I am able to echo the rooms into the venues, but I am struggling to restrict the rooms to ONLY appear with their unique parent venue. There is something simple that i am not seeing, I just know it.
//VENUE w VENUE ROOMS ARRAY TEST 2
$selCity = $_GET['theOption']; //Per Comment below modified $_POST to $_GET
$result5 = mysql_query("SELECT *
FROM lookup_venue_room INNER JOIN lookup_venue
ON lookup_venue_room.venue_name = lookup_venue.venue_name
WHERE lookup_venue.venue_city = '$selCity'
AND lookup_venue.venue_name = lookup_venue_room.venue_name") or die('ERROR' . mysql_error());
$roomNames = array();
$venueNames =array();
while($row2 = mysql_fetch_array($result5)) {
$roomNames[] = $row2['venue_room_name'];
$venueNames[] = $row2['venue_name'];
}
$result6 = mysql_query("SELECT * FROM lookup_venue WHERE lookup_venue.venue_city = '$selCity'")
or die('ERROR:' . mysql_error());
while($row = mysql_fetch_array($result6))
{
echo '<h3>' . $row['venue_name'];
echo '<select name="rooms">';
$venueNameOrig = $row['venue_name'];
foreach ($roomNames as $roomName) {
if ($row2['venue_name'] == $venueNameOrig ) {
echo '<option value="' . $roomName . '" selected="selected">' . $roomName . '</option>';
}
else {
echo '<option value="None">Non-venue-name-match</option>';
}
}
echo '</select>';
}

PHP: Merge two MySql array result

i fetch id and name from categories table like this :
|id|name| tag |desc|order|status|
|1 |test| NULL|NULL| 1 | 1 |
$i = 0;
$allcats = Access::FETCH("SELECT * FROM " . CATS . "");
$cats = array();
foreach($allcats AS $row2){
$cats[$i] = array("name" => $row2['name'], "id" => $row2['id']);
$i++;
}
i fetch category id for each news :
|id|catid|storyid|
|1 | 1 | 5 |
$groupcats = Access::FETCH("SELECT * FROM " . GROUPCATS . " WHERE storyid = ?", $row['postid']);
Now, i need to print name of cat for storyid. i,e : i need to print test(catname) for story id 5.
How do can i print this?
Easier to do with with a join rather than in php. Something like,
$joinedcats = Access::FETCH("SELECT name FROM " . CATS .
" JOIN " . GROUPCATS . " ON catid = id");
foreach($joinedcats as $row) {
echo $row['name'];
}
See https://dev.mysql.com/doc/refman/5.5/en/join.html
You can use join to get needed rows for each story:
"SELECT * FROM " . GROUPCATS . " LEFT JOIN " . CATS . " USING(categoryid) WHERE storyid = ?"

for each category row products

i'm having 3 tables.
module_names (module_id , module_name, module_content)
module_groups (group_id,group_name,group_content)
module_to_group (module_id,group_id)
I'm using the following query to get the results:
$result = $db->sql_query("select
m.module_id,
m.module_name,
g.group_name
from
" . $prefix . "_mmmodule_names m ,
" . $prefix . "_mmmodule_to_group m2g,
" . $prefix . "_mmmodule_groups g
where
m.module_id = m2g.module_id
and
m2g.group_id = g.group_id
and
g.group_id = g.group_id
order by
m.module_id");
while($row = $db->sql_fetchrow($result)) {
$content .= '<div>' . $row['group_name'] . '</div>';
$content .= '<div>' . $row['module_name'] . '</div>';
}
echo $content;
it output like this:
Group1
Module1
Group1
Module2
Group2
Module3
Group2
Module4
But i require it like this:
Group1
Module1
Module2
Group2
Module3
Module4
It has been a long time ago i made something like it.
For what i can remember i used for each.But of course the resources i had back then , are now not the top 10 search results anymore in google.
(Groupconcat is not an good idea for me to use)
$result = $db->sql_query("select m.module_id, m.module_name, g.group_name from " . $prefix . "_mmmodule_names m , " . $prefix . "_mmmodule_to_group m2g, " . $prefix . "_mmmodule_groups g where m.module_id = m2g.module_id and m2g.group_id = g.group_id and g.group_id = g.group_id order by m.module_id");
$modules = array();
while ($row = $db->sql_fetchrow($result)) {
$modules[$row['group_name']][] = $row['module_name'];
}
foreach ($modules as $groupName => $moduleNames) {
echo "<h2>$groupName</h2>";
foreach ($moduleNames as $moduleName) {
echo "<p>$moduleName</p>";
}
}
Just remembering last group name will not suffice since they can be mixed, another solution may be to add ordering for the group name in your query, in that case you can be sure that groups won't mix.
Everything's very simple. Just "remember" the last group name, and don't echo it until you've got the next one.
$tmpGroupName = null;
$result = $db->sql_query("select m.module_id, m.module_name, g.group_name from " . $prefix . "_mmmodule_names m , " . $prefix . "_mmmodule_to_group m2g, " . $prefix . "_mmmodule_groups g where m.module_id = m2g.module_id and m2g.group_id = g.group_id and g.group_id = g.group_id order by m.module_id");
while($row = $db->sql_fetchrow($result)) {
if ($tmpGroupName != $row['group_name'])
{
$tmpGroupName = $row['group_name'];
$content .= '<div>' . $row['group_name'] . '</div>';
}
$content .= '<div>' . $row['module_name'] . '</div>';
}
echo $content;
On solution could be to save state, by state I mean make a variable above the while loop and save groups title names is it (example Group 1) and at first iteration which the variable is null you can print title as well but for next iteration check and see if title in loop is equal to what is stored in the variable is which state is saved.
If they are equal you can pass printing title again and if not it means its new group coming and you can print title as well.
about content (for each title) you can print then in each iteration without any conditions.

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.

Categories