getting a result of a table Mysqli left join - php

So what i want is the following. I have 3 tables: first i will explain in english what i want for final result:
let me explain all in english:
table 1 is REGISTERED_MEMBERS
table 2 is OPEN CLASSES
table 3 i want who appplied and to which class they applied and show that in a table when date is selected from a dropdown list!
This is how it should show at the end:
table = razpisani_tecaji with (ID_TECAJA, DATE, STATUS, ST_ODPRTIH_MEST)
table = registrirani_clani wtih (ID_TECAJNIKA,IME,PRIIMEK, EMAIL)
table = prijave_na_tecaj with (ID_TECAJNIKA, ID_TECAJA, PLACILO)
now in HTML i have a dropdown list populated with dates (this works ok) from table 1.
<form>
<select name="dates" onchange="showUser(this.value)">
<option value="" selected="selected">Izberi datum za pregled</option>;
<?php
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = mysqli_query($con, "SELECT ID_TECAJA, DATUM FROM razpisani_tecaji");
while ($row = $sql->fetch_assoc()){
echo "<option value='" . $row['ID_TECAJA'] . "'>" . $row['DATUM'] . "</option>";
}
?>
Here a ID is saved to a variable q which is then send to php via JS. This all works. Now what i would like is for user to select a date and get a results from 3. table only to show IME from linked to ID_TECAJNIKA and PLACILO linked to ID_TECAJNIKA.
THis is what i have in PHP so far:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT razpisani_tecaji.ID_TECAJA, registrirani_clani._ID_TECAJNIKA FROM prijave_na_tecaj
LEFT JOIN razpisani_tecaji ON prijave_na_tecaj.ID_TECAJA = razpisani_tecaji.ID_TECAJA
LEFT JOIN registrirani_clani ON prijave_na_tecaj.ID_TECAJNIKA = registrirani_clani.ID_TECAJNIKA";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Ime</th>
<th>Placilo</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ID_TECAJNIKA'] . "</td>";
echo "<td>" . $row['PLACILO'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

$sql="select registrirani_clani., prijave_na_tecaj.,razpisani_tecaji.*
from registrirani_clani
left join prijave_na_tecaj on registrirani_clani.ID_TECAJNIKA = prijave_na_tecaj.ID_TECAJNIKA
left join razpisani_tecaji ON razpisani_tecaji.ID_TECAJA = prijave_na_tecaj.ID_TECAJA
where razpisani_tecaji.ID_TECAJA = '".$q."'";

Related

MySQL Result Prints More Than One

In my database I have a one-to-many table relationship where one parent can have many kids. The primary key is the parents email. I query to get the kids
$results1 = mysqli_query($con,"
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON '$row[email]' = dirKids.parent
");
Then I loop through and echo the value to my html page
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>".
$row1["kbirthday"]."</td></tr>";
}
}
The problem I am having is that only one parent has kids in my database, but it will print the kids name and birthday 10 times because there are 10 people in my database. How can I get it to only print the child's name and birthday once?
My full code is listed below:
<?php
$con = mysqli_connect("localhost", "username", "password", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($con,"SELECT directory.id, directory.fname, directory.lname, directory.address, directory.bdname, directory.birthday, directory.cell, directory.email, directory.sFName, directory.sBirthday, directory.sCell, directory.sEmail FROM directory ORDER BY lname") or die ("couldn't fetch query");
echo "<div class='accordion' id='accordion'>";
// output data of each row
while($row = mysqli_fetch_array($results)) {
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
echo "</table></div>";
if ($row['sFName'] == "" || $row['sFName'] == "undefined") {
echo "<div class='card'><div class='card-header'
id='headingOne'><h5 class='mb-0'><button class='btn btn-link'
type='button' data-toggle='collapse' data-target='#collapse".
$row["id"] ."' aria-expanded='true' aria-controls='collapse".
$row["id"] . "'><h5>".$row["fname"] ."<span id='lnameText'>".
$row["lname"] ."</span></h5></button></h5></div><div
id='collapse". $row["id"] . "' class='collapse'
aria-labelledby='headingOne' data-parent='#accordion'><div
class='card-body'><table id='myUL' class='table'><tr></tr><tr>
<td><h5>Address</h5></td><td>". $row["address"] ."</td></tr>
<tr><td><h5>Birthday</h5></td><td>".$row["birthday"]."</td>
</tr><tr><td><h5>Cell</h5></td><td>". $row["cell"]."</td></tr>
<tr><td><h5>Email</h5></td><td>". $row["email"] ."</td></tr>
</table></div>";
echo "<div class='col-md-6'><h3>Children</h3><table class='table'><tr><th><h5>Name</h5></th><th><h5>Birthday</h5></th>";
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>". $row1["kbirthday"]."</td></tr>";
}
}
echo "</table></div></div>";
?>
Since the data needed for the second while loop comes exclusively from the kids table, just build your SELECT statement for that, forget the join and the WHERE statement looks for only the parents email.
The below code goes inside the primary while loop and replaces the
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
with
//Build the select statement
$sql = "SELECT kname, kbirthday FROM dirKids WHERE parent = '" .$row[email] . "'";
//now run the query
$results1 = mysqli_query($con,$sql);
//uncomment the below to see the results
//var_dump(mysqli_fetch_array($results1));
Your query should look like this;
$select = mysqli_query($db, "SELECT * FROM parents_database WHERE parent_name = '$parent_name'");
while ($row = mysqli_fetch_array($select, MYSQLI_ASSOC)) {
// echo kids here..
}
Not sure what do you need. Since you posted 2 different queries.
But 1st one has wrong approach, hope you need to fix that one.
I think you've meant something like:
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON directory.email = dirKids.parent
WHERE directory.email = '$row[email]'

Count business class With same value

<?php
$con = mysql_connect("localhost","root","root");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mydb",$con);
//Count all Total of Acc Class with same value Example Restaurant, Hotel
$query = "select acc_class,count(*) as total from mytable group by acc_class";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$num_total = $values['total'];
while($record = mysql_fetch_array($result)){
echo '<br>';
echo "<label>" . $record['acc_class'] . "</label>";
echo "<label>" . $num_total . "</label>";
}
mysql_close($con);
?>
Guys please help me. I want to produce something like this. But I don,t know how.
Account Class Total
------------- -----------
Hotel 5
Restaurant 2
Club 3
Church 1
I want to have a page in which it will show total numbers of each account class. Please help.
Thanks!
//you just need to put the name of the column in quert like COUNT(column_name)
$con = mysql_connect("localhost","root","root");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mydb",$con);
//data base connection ends here
//you write a query to fire if you want by order the put "ORDER BY HERE"
$query = "select acc_class,count(acc_class) as total from mytable group by acc_class";
//here you fire a query to mysql
$result = mysql_query($query);
//now put the selected roe in loop and again and again loop ask for more data to mysql
while($record = mysql_fetch_array($result)){
**//here you select all the group in the table**
echo '<br>';
echo "<label>" . $record['acc_class'] . "</label>";
echo "<label>" . $record['total'] . "</label>";
}
//close connection to database
mysql_close($con);
Please dump $values:
var_dump($values);
I guess, the problem is it's either the data itself or the data-fetch (array, assoc).
Please format your SQL for better readability:
SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class;
The Count statement is correct: https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Solution:
$query = "SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class";
$result = mysql_query($query);
echo '<table border="1">';
while($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['acc_class'] . '</td>';
echo '<td>' . $row['total'] . '</td>';
echo '</tr>';
}
echo '</table>';

How to get the value from the primary key AND foreign key when joining mySQL tables?

I have two tables, employee as the parent and license as the child. They both have a Lic_ID column for reference, this column is the PK in license and the FK in employee. The license table also has a column Lic_Type which holds the name of the license.
I am trying to create a table with list boxes so the employee table can be updated. The list box value needs to be populated with the license.Lic_ID and the license.Lic_Type is to be displayed in the option. Here is what I have:
(Employee name, Id, etc. called out up here)
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT Lic_ID, Lic_Type FROM license");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['Lic_ID'] . "\">" . $row['Lic_Type'] . "</option>";
}
echo "</select>";
?>
So that works good, it shows the license type and has the value set to the license id. What I want to do is have <option selected="selected"> if the license id is set for an employee. This code doesn't work, but I think it illustrates what I'm trying to do:
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT license.Lic_ID, license.Lic_Type, employee.Lic_ID FROM employee INNER JOIN license ON employee.Lic_ID = license.Lic_ID");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['license.Lic_ID'] . "\"";
if($row['employee.Lic_ID'] = $row['license.Lic_ID']){echo "selected=\"selected\";}
echo ">" . $row['license.Lic_Type'] . "</option>";
}
echo "</select>";
?>
Is there a way to accomplish what I'm trying to do?
I think there may have been some confusion on what exactly I was trying to accomplish, I apologize for not being very clear. Anyways, I stumbled over the answer today, so I thought I should post it.
$sql1 = ("SELECT Emp_Name, Lic_MAT_ID FROM employee");
if(!$result_employee_query = $mysqli->query($sql1))
{
die ("There was an error getting the records from the employee table");
}
while($employee = $result_employee_query->fetch_assoc())
{
echo "Employee Name: " . $employee['Emp_Name'] . "<br>";
echo "License: ";
echo "<select>";
$sql2 = ("SELECT Lic_MAT_ID, Lic_MAT_Type FROM license_mat");
if(!$result_license_query = $mysqli->query($sql2))
{
die ("There was an error getting the records from the license table");
}
while($license = $result_license_query->fetch_assoc())
{
echo "<option value=\"" . $license ['Lic_MAT_ID'] . "\"";
if($license['Lic_MAT_ID'] == $employee['Lic_MAT_ID'])
{
echo " selected=\"selected\"";
}
echo ">" . $license ['Lic_MAT_Type'] . "</option>";
}
echo "</select><br>";
}
As I understand your problem: You want to see if the License has been added to ANY users or has it been unassigned. If any of the users have the license set then it's "selected", othervize not.
First you have to assign the keyword "multiple" to your select object to make it a listbox:
echo "<select name=\"Lic\" multiple=\"multiple\">";
Second: I would write this kind of query:
$sql = $mysqli->query("SELECT l.Lic_ID, l.Lic_Type, e.cnt FROM licence l left outer join (select Lic_id, count(*) cnt from employee group by Lic_id) e on l.Lic_ID=e.Lic_id");
It selects the Lic_ID, Lic_Type and the count of how many employees have the respective Lic_ID set to it (left outer join)
and in the code just check, if the count is higher then 0
if($row['cnt'] > 0){
echo "selected=\"selected\";
}

Php in MYSQL aggrate function not working

$result = mysql_query("SELECT avg(r.rate) FROM rate r where ImgName='1'");
this php is not working.
Originally my code is
<?php
$con = mysql_connect("localhost","root","sql");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("photogallery", $con);
$result = mysql_query("SELECT avg(r.rate) FROM rate r ");
echo "<table border='0' cellspacing='5'>";
echo "<th> Average Rating </td>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> " . $row['rate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
the above is not showing any out put.
but modify code i.e. then its workin.
$result = mysql_query("SELECT r.rate FROM rate r ");
but i want to aggregate function
thanks in advance
you can use an alias:
SELECT avg(r.rate) AS rate_average
FROM rate r
WHERE ImgName='1'
and then output:
echo "<td> " . $row['rate_average'] . "</td>";
Your query is producing a scalar rather than a set of rows. If you want to get the average rate per item then you should do something like:
SELECT avg(r.rate) FROM rate r GROUP BY ItemIdColumn
And yes, if you want to fetch the value by column name, you should use an alias, like knittl mentioned.

PHP and Multiple DB Selects

I've got two tables from which I need to extract information, but the data from the second table depends on the information I get from the first one. Is there an easy way to handle this?
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('stadium') or die(mysql_error());
$result = mysql_query("SELECT * FROM events");
$result2 = mysql_query("SELECT name FROM competitions WHERE id='$row[competition_id]' ");
while($row = mysql_fetch_array($result)) {
echo "<tr id=\"" . $row['id'] . "\"> \n<td>" . $row['name'] . "</td>";
echo "<td>" . $row['competition_id'] . "</td>";
echo "<td>" . $row['date'] . "</td></tr>";
}
?>
Use a JOIN.
SELECT e.*, c.name as competition_name FROM events e LEFT JOIN competitions c on c.id = e.competition_id

Categories