Can't display query when using inner join with php? - php

I have a drop down menu form like so: https://ibb.co/eX5BhH
Each selected option will filter the query and return the query. So far, my "disability" and "veteran" option are querying correctly. I'm trying to get the "Type of Resource" category to work by using inner join. Here's the sql command:
SELECT shelter_name, shelter_address, disability, veteran
FROM shelter s
INNER JOIN shelter_type st ON s.shelter_id = st.shelter_id
INNER JOIN s_type stt on st.type_id = stt.type_id
WHERE type_name = "Charitable Organization";
This sql command works but it only query the resources under the "Charitable Organization" category. The user will be able to choose other category so instead of "Charitable Organization" I replace it with "$value_4":
SELECT shelter_name, shelter_address, disability, veteran
FROM shelter s
INNER JOIN shelter_type st ON s.shelter_id = st.shelter_id
INNER JOIN s_type stt on st.type_id = stt.type_id
WHERE type_name = "$value_4";
Here is my php code:
<?php
require'/Library/WebServer/Documents/Require/require.php';
$value_1 = $_POST["county"];
$value_2 = $_POST["disability"];
$value_3 = $_POST["veteran"];
$value_4 = $_POST["resources"];
$sql = "SELECT shelter_name, shelter_address, disability, veteran
FROM shelter s
INNER JOIN shelter_type st ON s.shelter_id = st.shelter_id
INNER JOIN s_type stt on st.type_id = stt.type_id
WHERE type_name = '$value_4'";
$result = mysqli_query($dbc, $sql) or die (mysql_error());
echo"<table border='1'>";
echo"<tr><td>Shelter</td><td>Address</td><td>Disability</td></tr>";
//iterate through the table
while ($row = mysqli_fetch_assoc($result)){
echo"<tr><td>{$row['shelter_name']}</td><td>{$row['shelter_address']}</td><td> {$row['disability']}</td><td>{$row['veteran']}</td></tr>";
}
echo"</table>"; //close table
echo"success";
?>
However, when I use "$value_4", the table doesn't display. If I change it back to "Charitable Organization", the table is displayed again. What can I do to make my table display when I use "$value_4"?

I think to resolve this issue you should be using LEFT JOIN rather than INNER JOIN.
Inner Joins expect data from the left table and right table to match. If it only exists in the left table but not the right then it won't show the records.
By using Left Join you are saying you want everything from the left table and then if there is information from the right table (i.e. the one you're joining on) then bring that too.
It might be worth reading this tutorial on joins to help you get more experience.

Related

Select Mysql Query inside echo of another query

Hello I would like to know how I can realizes query selection inside echo of already processed query.
This is my firs Mysql Query
SELECT * FROM cursos_modulos
foreach($result as $row)
{
$id = $row['id'];
echo"
Here where the echo goes I have to make the other query which is:
SELECT COUNT(users.userID)
FROM users
INNER JOIN subscriptions
ON users.userID = subscriptions.user_id
WHERE subscriptions.curso_id = $id
and at the end to put the result of this query
foreach($result as $rowc)
.$rowc[0]."};
Any help how I can achive this goal will be very welcome. Question is simple. First Select Selects the Cours with it's unique ID. which ID have to be used in the second, third and else... queries. Which queries are like the second one. So First Select Course and then Select different parameters from this course based on this ID. at the end dump results of each of the selections with different indications"
Do it all in one query:
SELECT c.*, count(s.curso_id) as count
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id
The LEFT JOIN is needed to get 0 for the count if there are no matching rows in subscriptions.
To include a second count of approved subscriptions:
SELECT c.*, count(s.curso_id) as count, SUM(IF(s.approved = 'approved', 1, 0)) AS count_approved
FROM cursos_modulos AS c
LEFT JOIN subscriptions AS s ON s.curso_id = c.id
LEFT JOIN users AS u ON u.userID = s.user_id

Merging two queries with the same binded parameter

I have a first SQL query getting a table with id_member as parameter
$stmt = $mysqli -> prepare("SELECT a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
FROM alerte a,
alerte_par_roster ar,
roster_par_membre rm
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE rm.id_roster = ar.id_roster
AND ar.id_alerte = a.id_alerte
AND rm.id_membre = ?");
$stmt->bind_param('i', $id_membre);
I need to insert a second query counting the number of lines in another table.
The second query is:
"SELECT COUNT(DISTINCT id_roster)
FROM disponibilites_par_member_alertes
WHERE id_member = ?
AND id_alerte = ?"
As you can notice id_member is the identical in both queries but id_alerte (used as a parameter of the second query is a result of a first query).
I hope I am clear.
Any idea will be very welcome
I don't fully understand what your queries are intended to do. It would help to have clear information on the table structure and what each of the fields represents. I've tried to make a guess based on the table names but can't be certain it's correct.
The first thing I did was just to transform your WHERE condition such that each of the tables are joined explicitly. This is just for readability.
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
WHERE
rm.id_membre = ?
Now we combine with the other query:
SELECT
a.id_alerte,
a.nom_alerte,
ar.id_roster,
r.nom_roster,
rc.id_roster_count
FROM alerte a
INNER JOIN alerte_par_roster ar
ON ar.id_alerte = a.id_alerte
INNER JOIN roster_par_membre rm
ON rm.id_roster = ar.id_roster
INNER JOIN roster r
ON r.id_roster = rm.id_roster
LEFT JOIN (
SELECT id_membre, id_alerte, COUNT(DISTINCT id_roster) AS id_roster_count
FROM disponibilites_par_member_alertes
GROUP BY id_membre, id_alerte
) AS rc
ON rc.id_membre = rm.id_membre
AND rc.id_alerte = ar.id_alerte
WHERE
rm.id_membre = ?
With my own generated data I get results like this:
If this is not enough to solve the problem you will need to provide more details about the tables and the design.

Three times INNER JOIN SELECT

I've a page where I want to use 3 times INNER JOIN, Because log_items have a row called 'price'. When I do INNER join with log_mobs & log_mitem everything goes fine, He gets all information from $_GET['id'] combined with ['g'] but when I join with log_items he shows all rows from the table 'log_items'
I want to show on the page, the items the MOB have next to that I want to show the price.
But he shows all those information from 'log_items' I need to show items from 'log_mitem' but I need to get those prices from 'log_items'
if (isset($_GET['id']) && isset($_GET['g']))
{
$id = $db->real_escape_string(trim($_GET['id']));
$g = $db->real_escape_string(trim($_GET['g']));
$mobitem = $db->query("SELECT * FROM log_mobs INNER JOIN log_mitem INNER JOIN log_items ON log_mobs.name = log_mitem.mobname AND log_mobs.game = log_mitem.game WHERE log_mobs.name = '".$id."' AND log_mitem.game = '".$g."'") or die($db->error);
?>
I think your SQL request should look something like this:
select * from log_mobs
inner join log_mitem on log_mobs.name = log_mitem.mobname
inner join log_items on log_items.column = theOtherSideOfTheJointure.column

I would like to expand a SQL query to also get the name of the ID's it is selecting. How do I do that?

At the moment I have a very basic SQL query, however I would like to expand it in order to fetch the names of the ID's it is referencing as well. The problem is, it's a Parent > Child relationship table. The Parent and Children items are part of the same table, but different rows.
$GetRelations = "
SELECT RelationUID, BlockTypeUID, ChildBlockUID, Weight FROM block_type_relations
WHERE BlockTypeUID = '$BlockTypeUID'
";
When I only have a single BlockTypeUID to initially fetch the records, how can I shift this query around so that it also fetches the names from table block_types for both BlockTypeUID and ChildBlockUID? I'm writing this in mySQLi.
Assuming the name is in a column named "name", the query could look like this
$GetRelations = "
SELECT a.RelationUID, a.BlockTypeUID, a.ChildBlockUID, a.Weight
b.NAME AS BlockTypeName, c.NAME AS ChildBlockName
FROM block_type_relations a
INNER JOIN block_types b ON b.ID = a.BlockTypeUID
INNER JOIN block_types c ON c.ID = a.CildBlockUID
WHERE a.BlockTypeUID = '$BlockTypeUID'
";
$GetRelations = "SELECT btr.RelationUID, btr.BlockTypeUID, btr.ChildBlockUID,
btr.Weight,bt.Name FROM block_type_relations btr
INNER JOIN block_types bt ON bt.BlockTypeUID =btr.BlockTypeUID
WHERE BlockTypeUID = '$BlockTypeUID'";

get count of posts based on count(*)

i am trying to get number of posts that i have
Here is my query
$Query="
SELECT t.*,u.*,c.*
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
This query is works very well
but i am trying to convert it, i want make it faster
i want use count(*) instead of t.*
because when i use t.*, it gets the full data of posts and categories
but i want to get count only, So i decided to use count(*) but i don't know how to use it with query like this
Edit
i've replaced SELECT t.*,u.*,c.* with SELECT count(t.*)
But i got mysql Error Warning: mysql_fetch_assoc(): supplied argument
Edit 2:
i am trying SELECT count(t.post_title)
I Got this results
Array ( [count(t.post_id)] => 10 )
But i have only 2 posts!
$Query="
SELECT t.*,u.*,c.*
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
Let's take a step back and analyze this query for a moment.
You're selecting everything from three out of four tables used in the query. The joins create some logic to limit what you select to the proper categories, authors, etc. At the end of the day you are getting a lot of data from the database, then in PHP simply asking it how many rows were returned (mysql_num_rows). Instead, what #Dagon is trying to suggest in comments, is that you have MySQL simply count the results, and return that.
Let's refactor your query:
$query = "
SELECT COUNT(t.post_id) AS qty
FROM posts as t
LEFT JOIN relations AS r ON r.post_id = t.post_id
LEFT JOIN users AS u ON t.auther_id = u.auther_id
LEFT JOIN categories AS c ON c.cate_id = r.cate_id
GROUP BY t.post_id
";
$result = mysql_query($query);
$result_row = mysql_fetch_assoc($result);
$numberOfPosts = $result_row['qty'];
(You could also use Barattlo's custom execute_scalar function to make it more readable.)
I would need to see your table structures to be of more help on how to optimize the query and get the desired results.
try doing this:
$Query="
SELECT count(t.*) as count_all
FROM posts as t
LEFT JOIN relations as r on r.post_id = t.post_id
LEFT JOIN users as u on t.auther_id = u.auther_id
LEFT JOIN categories as c on c.cate_id = r.cate_id
GROUP BY t.post_id
";
$Query=mysql_query($Query);
$numberOfPosts=mysql_num_rows($Query);
You want to do
SELECT count(t.id) AS count FROM ....
//do query with PDO or whatever you are using
$rows = mysql_fetch_assoc();
$num_rows = $rows['count'];
You should probably simply use
SELECT count(*) as postingcount FROM posts
Why?
Because you do not have a WHERE clause, so there are no restrictions. Your JOINS do not ADD more rows to the resultset, and in the end your GROUP BY merges every duplicate occurance of a post_id that might have occurred because of joining back into one row. The result should only be counted, so assuming that the real number you want to know is the number of data sets inside the table posts, you do not need any join, and doing count(*) really is a very fast operation on tables in MySQL.
Remember to check if mysql_query returns false, because then you have to check mysql_error() and see why your query has an error.

Categories