How To Join Tables Inside Join in PHP MYSQL - php

I have some tables for my data cafe. The tables are tb_cafe for main table, tb_fasilitas that has id_cafe from tb_cafe and id_fasilitas from tb_fasilitascafe. Then tb_lokasicafe, tb_menucafe, tb_gallerycafe.
I just wanted to get all data from tb_cafe and facility name, location, menus, and price.
Is it possible to join tb_facilitycafe with tb_facility to get name facility by id_cafe inside join query for another table? Can you show me how to resolve this.
I use it for an API that results in JSON output.
I tried the code like this:
<?php
include_once('koneksi.php');
$sql = "SELECT * FROM tb_cafe AS tc
LEFT JOIN tb_fasilitas_cafe AS tf ON tf.id_cafe=tc.id_cafe
LEFT JOIN tb_gallerycafe AS tg ON tg.id_cafe=tc.id_cafe
LEFT JOIN tb_lokasicafe AS tl ON tl.id_cafe=tc.id_cafe
LEFT JOIN tb_menucafe AS tm ON tm.id_cafe=tc.id_cafe
WHERE state_verifikasi IN (1)";
$r = mysqli_query($con,$sql);
$result = array();
if($r){
while($row = mysqli_fetch_array($r)){
array_push($result,array(
"id_cafe"=>$row['id_cafe'],
"nama_cafe"=>$row['nama_cafe'],
"foto_cafe"=>$row['foto_cafe'],
"alamat_cafe"=>$row['alamat_cafe'],
"deskripsi_cafe"=>$row['deskripsi_cafe'],
"no_telepon"=>$row['no_telepon'],
"jam_operasional_WeekDay"=>$row['jam_operasional_WeekDay'],
"jam_operasional_WeekEnd"=>$row['jam_operasional_WeekEnd'],
"nama_fasilitas"=>$row['nama_fasilitas'],
"foto"=>$row['foto'],
"latitude"=>$row['longitude'],
"longitude"=>$row['longitude'],
"nama_menu"=>$row['nama_menu'],
"harga_menu"=>$row['harga_menu']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>
I wanted to get a specific result by the id_cafe, but the result I have shows more than 1 result for the same id_cafe. How can I fix it to be 1 result for one id_cafe?

Related

PHP display $rows from inner table

Like on title... how to display row data from inner join table if name of the row are the same?? but data is diffrent?
$sql = "SELECT fv.name,fvcount.name,fvcount.datew,fvcount.u_uid
FROM fv
INNER JOIN fvcount ON fv.u_uid = fvcount.u_uid ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo $row['u_uid'];
}
Result will be printed, but on both table 1 of the rows name is like: name
So if i put
$row['name'];
i will have output of inner join table
How to get output from main table and inner joint table?
I can't change name of the row...
Any clue?
The typical solution is to use column aliases. You can do something like:
SELECT fv.name AS fv_name, fvcount.name as fvcount_name, ...
And then use:
$row['fv_name']
Or:
$row['fvcount_name']

Echo contents of JOIN SQL tables with MySQLi

I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}

PHP MySQL - How to fetch the SELECT GROUP_CONCAT,GROUP_BY two table?

I have two database tables like this and want to fetch to my website like this(see the screenshot)
But I can only fetch one table. I don't know how to use group by with JOIN
here is my code
$sql = "SELECT photographer,GROUP_CONCAT(free_image)
FROM free_images_table
GROUP BY photographer";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$free_image = explode(',', $row['GROUP_CONCAT(free_image)']);
echo "<tr>";
echo "<td>".$row['photographer_id']."</td>"; ?>
<td>
<?php
for($i=0; $i < count($free_image); $i++ )
{
echo $free_image[$i];
}
?></td>
echo "</tr>";
}
The special table may not have photographer (my website require only freeimage, the special image is optional.
This could be done using a LEFT JOIN (added column aliases for simplicity in php) -
SELECT free_images_table.photographer,
GROUP_CONCAT(DISTINCT free_images_table.free_image) as free_images,
GROUP_CONCAT(DISTINCT special_images_table.special_image) as special_images
FROM free_images_table
LEFT JOIN special_images_table
ON special_images_table.photographer = free_images_table.photographer
GROUP BY photographer
LEFT JOIN is used when you have a record in the 1st table, but not always a matching record in the 2nd table
Then in php, you would create your special image cells the same as your free image cells
$free_image = explode(',', $row['free_images']);
$special_image = explode(',', $row['special_images']);
...
SELECT table_1.free_image, table_2.special_image FROM table1 INNER JOIN table_2 ON table_1.photographer = table_2.photographer
In this case can use INNER JOIN.
Add table name before the field and INNER JOIN with same photographer.

How to get all the data from mysql using PHP

As you can see inside my while loop i declare i variable $TYPES..
This is my first Query
$first = "SELECT DISTINCT DATE_FORMAT(z.DatePaid,'%M %d, %Y') AS Paid
FROM tblStudPayments z
INNER JOIN tblPersonalData p ON p.StudNo=z.StudNo
WHERE z.StudNo=p.StudNo AND z.SY='".$SY."' AND z.Sem='".$Sem."' ORDER BY z.DatePaid;";
$fs = safe_query($first);
$numrows = mysql_num_rows($fs);
if($numrows>0)
{
while($dataf = mysql_fetch_assoc($fs))
{
$types =$dataf['Paid'];
}
}
I wanted to pass the value of $TYPES to my second Query
And This is my Second Query
$sql="SELECT DISTINCT p.StudNo, p.LName, p.FName, p.MName, p.NName, c.Description, p.YearLevel, d.Status,
'".$types."' AS DateEnlisted,
FROM tblPersonalData p
INNER JOIN tblStudPayments sp ON sp.StudNo=p.StudNo AND sp.SY='".$SY."' AND sp.Sem='".$Sem."'
INNER JOIN tblStatusHistory d ON d.StudNo=sp.StudNo AND d.SY=sp.SY AND d.Sem=sp.Sem
INNER JOIN tblCourses c ON c.CourseCode=d.CourseCode AND c.HSOrCollege='".$dType."'
INNER JOIN tblUserAcct u ON u.UserName=p.StudNo
";
$sql.=" HAVING DateEnlisted = '".$a['DateEnrolled']."' ";
$sql.=" ORDER BY p.StudNo ASC;";
At the bottom of SELECT Statement you can see my variable $TYPES i get it from my first query.
The problem is it doesn't get all the data.. it only get the last data from mysql
Thanks in Advance..
[Image Suggested by Kundu Updated][1]
[Image Suggested by Kundu echo $sql][2]
i try one query but the loading of data takes 10-15MIN.
Put the 2nd query inside the 1st query while loop
In your while loop you put the value in a variable & evry time this variable is updated.So at the end of the loop it will return last type value. Either put it in a array, so it will store all the value.But that case you need to convert the array into string when you put it in 2nd query.Also make sure when you put value in $type it should be unique.
update your code like this:
$types=array();
while($dataf = mysql_fetch_assoc($fs))
{
$types[] = $dataf['Paid'];
}
$allTypes = implode(",`", array_unique($types));
Now in your query:
$sql="SELECT DISTINCT p.StudNo, p.LName, p.FName, p.MName, p.NName, c.Description, p.YearLevel, d.Status,
`".$allTypes."` AS DateEnlisted,
FROM tblPersonalData p
INNER JOIN tblStudPayments sp ON sp.StudNo=p.StudNo AND sp.SY='".$SY."' AND sp.Sem='".$Sem."'
INNER JOIN tblStatusHistory d ON d.StudNo=sp.StudNo AND d.SY=sp.SY AND d.Sem=sp.Sem
INNER JOIN tblCourses c ON c.CourseCode=d.CourseCode AND c.HSOrCollege='".$dType."'
INNER JOIN tblUserAcct u ON u.UserName=p.StudNo
";

PHP MYSQL query - Strip away columns from response

Is it possible to strip away columns from the response I get in a query where I join 3 tables and need more or less all columns for the query itself so that some columns aren't visible in the response?
This is the query I have:
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_subApp.*,
tbl_tag.*
ISNULL(tbl_userDeviceNOTTag.userDevice_id) AS selected
FROM tbl_subApp2Tag
LEFT JOIN tbl_subApp
ON tbl_subApp.id = tbl_subApp2Tag.subApp_id
AND tbl_subApp.subApp_id = '".$sub."'
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDeviceNOTTag
ON tbl_userDeviceNOTTag.tag_id = tbl_tag.id
AND tbl_userDeviceNOTTag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = tbl_subApp.id
ORDER BY tbl_tag.name ASC ");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
You do not need to include columns in the result table, just because they are referenced elsewhere in the query. Just select the columns that you need.

Categories