Comparing two SQL tables - php

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

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.

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

PHP Display MYSQL Results within a loop

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
}

How to add up votes in a table and display it on screen

i have a php code which selects and shows data from my 'elections' table. i have another table called 'votes' which contains all the votes by users. how do i select the two tables and show the party that has had the most votes? so if labour had 5 votes for example and lib dems had 3 votes, how would i show on screen that 'labour has won this election with __ votes? my php is as follows:
<?php
$id = $_GET['election'];
$result = mysql_query("SELECT election_id, name_of_election, date, month, year FROM elections WHERE election_id = '$id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo '<hr><h3>There Aren\'t Any Elections Setup Yet</h3><hr> ';
} else {
echo '<hr><h3>Vote Count</h3><hr>';
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name_of_election']. "</td>";
echo "<br/><br/><td>" . $info['date']. ' '. $info['month']. ' ' . $info['year']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
}
echo "</tr>";
echo "</table>";
?>
my database table consists of the following fields:
(dont ask about the date fields)
elections: election_id, name_of_election, date, month, year, party1, party2, party3, status
votes: vote_id, election_id, ni, party
any ideas?
This will give you the party and count for selected election in descending order of count:
$result = mysql_query(
sprintf("
SELECT votes.party, COUNT(votes.vote_id)
FROM votes
WHERE election_id = %d
GROUP BY election_id, votes.party
ORDER BY COUNT(votes.vote_id) DESC",
mysql_real_escape_string($id)
)
);
Edit: To display the first row (which will be the party with the most votes):
list($party, $votes) = mysql_fetch_row($result);
echo '<p>'.$party.' won with '.$votes.'</p>';

Categories