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

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

Related

count rows with same id and print

So I have this table 'users_photos'. It contains 38k rows with user pictures. Every row contains id, userid and link to the photo. So if a user have 3 pictures, that user id will show in 3 rows in the database.
What I want to do is count the number of users with 1 picture in the database, 2 pictures in the database etc.
UPDATE: I have now the following code
$sql = $mysqli->query("SELECT count(*), count_users from (SELECT u_id, count(*) as count_users FROM users_photos group by u_id) temp group by count_users");
$sql->data_seek(0);
while ($row = $sql->fetch_assoc()) {
echo "".$fetch." = " . $row['count_users'] . "\n<br>";
}
This prints the users that have 1 picture and up to 8. Not how many but only shows that in the database there is users that have 1 picture, 2 pictures etc. Now I need to figure out how to print the total users that have 1 picture etc.
Anyone have any tips? thanks on behalf!
Update Your Query With This
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
Sql Query:
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
You Can Print like this
// After Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - count_users" . $row["count_users"]. "<br>";
}
} else {
echo "0 results";
}
You can do something like this:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$sql = 'SELECT u_id, count(*) AS count_users FROM users_photos GROUP BY u_id';
$result = mysqli_query($con, $sql);
while ($row=mysqli_fetch_assoc($result)) {
echo 'User id: ' . $row['u_id'] . ' Count: ' . $row['count_users'] . '<br>';
}
Keep in mind this is just a basic example. In a real world application there is more to do such as checking for errors.

SQL Join Statement To Update an Entire Column with PHP Loop

I need to update an entire column with new unique phone numbers that live in a second table. I seem to be on the right track... but my loop logic is faulty.
I'm returning the matches correctly as far as I can tell, but when I try to update the entire column in the table it inserts the last phone number in every single row.
$query = "SELECT matched.duns, matched.new_p1, users_data.temp_duns
FROM matched
INNER JOIN users_data ON temp_duns
WHERE temp_duns = duns LIMIT 10";
$result = mysqli_query($connection, $query);
foreach ($result as $key => $val) {
if($val['duns'] === $val['temp_duns']) {
$final_query = "UPDATE users_data SET phone_number = " . $val['new_p1'];
$final_result = mysqli_query($connection, $final_query);
echo $counter . "DUNS From matched: " . $val['duns'] . " DUNS From users_data: " . $val['temp_duns'] . " NEW PHONE: ". $val['new_p1']. "<br>";
}
}
I'm a total newb but any help would be appreciated.
Simply run an update query in one call without looping and in MySQL INNER JOIN can be used:
UPDATE user_data u
INNER JOIN matched m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;
Or for the limit of 10:
UPDATE user_data u
INNER JOIN (SELECT * FROM matched LIMIT 10) m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;
The problem is that your query doesn't have a WHERE clause, so it's updating every row.
"UPDATE users_data SET phone_number = " . $val['new_p1'];
You need to limit it to just the row that you want to update.
"UPDATE users_data SET phone_number = " . $val['new_p1'] . " WHERE some_id = " . $some_id;
You could probably do the whole thing in a single query.
UPDATE table_to_be_updated
JOIN table_with_value_we_need ON whatever_joins_them
SET table_to_be_updated.column_we_want_to_fill = table_with_value_we_need.value_we_need;

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

How to select information from 2 tables?

I am trying to get data from two tables:
$con = getDbConnect();
$edit = $_GET['edit'];
if (mysqli_connect_errno($con)) {
"Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$result = mysqli_query($con, "SELECT * FROM admininfo where email='" . $edit . "'");
$results = mysqli_query($con, "SELECT * FROM adminaccount where email='" . $edit . "'");
while ($admininfo = mysqli_fetch_array($result, $results)) {
You use a single query no matter how many tables you're selecting from, e.g.
SELECT a.*, b.* FROM table1 a, table2 b where a.id = ? AND b.id = ?
Then you fetch what you need from the result, take a look at the docs for that.
-- and, of-course, don't use select *.

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