Multiple mysql table joins with php? - php

Honestly I have no idea how to do what I am trying to do. I am not overly experienced in php nor in Mysql but I am trying and could use some help, preferably with working example code.
Problem: I have 3 tables
members
customfields
customvals
members contains:
membername | Id
customfields contains:
rank | name
customvals contains
fieldid | userid | fieldvalue
Table columns match at
customvals.userid=members.id
customvals.fieldid=members.rank
What I need to do is match the data so that when page.php?user=membername is called it displays on the page
Table1.membername:<br>
Table2.name[0] - Table3.fieldvalue[0]<br>
Table2.name[1] - Table3.fieldvalue[1]<br>
etc...
(obviously displaying only the information for the said membername)
The more working the code, the more helpful it is for me. Please don't just post the inner join statements. Also it is most helpful to me if you could explain how and why your solution works
So far here is what I have for code:
$profileinfocall = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`membername` = $username;";
$membercall = "SELECT * FROM members WHERE membername=$username";
$profileinfo = mysql_query($profileinfocall, $membercall);
while($row = mysql_fetch_array($profileinfo)) {
echo $row['membername'];
}
Obviously this doesn't work as I get the following errors:
Warning: mysql_query() expects parameter 2 to be resource, string given on line 534.
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in on line 535

While this is a very broad question and you have not provided any PHP code, you might want to break it down into various sections:
Establishing a connection to the database (with mysqli) and sending a query:
$c = mysqli_connect("localhost","user","password","db");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
else {
$result = mysqli_query($c,"SELECT * FROM members");
while($row = mysqli_fetch_assoc($result)) {
echo "{$row['membername']}";
}
}
mysqli_close($c);
Tieing your tables together:
It is better to start off with a clear structure (including line breaks) when getting into the MySQL syntax. One way would be to have some sort of query skeleton:
SELECT tablealias.column, table2alias.field3
FROM table AS tablealias
LEFT|RIGHT|INNER JOIN table2 AS table2alias ON table.id=table2.id
WHERE (this and that = true or false, LIKE and so on...)
Breaking it down to your specific problem this would be:
SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE Table1.`Id` = 'UserID to be searched for'
Improvements & Security measures:
But there is even more to it than meets the eye. If you have just begun, you might as well dive directly into prepared mysqli- statements. Given the query to get your members, the only changing part is the ID. This can be used for a prepared statement which is much more secure than our first query (though not as fast). Consider the following code:
$sql = "SELECT Table1.`membername`, Table2.`name`, Table3.`fieldvalue`
FROM members AS Table1
LEFT JOIN customvals AS Table3 ON Table1.`id` = Table3.`userid`
LEFT JOIN customfields AS Table2 ON Table3.`fieldid` = Table2.`rank`
WHERE (Table1.`Id` = ?)";
$c = mysqli_connect("localhost","user","password","db");
$stmt = $c->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_params("i", $userid);
$stmt->execute();
while ($stmt->fetch()) {
//do stuff with the data
}
$stmt->close();
}
$mysqli->close();

This SQL query should do it:
SELECT a.membername, a.Id, b.fieldid, b.userid, b.fieldvalue, c.rank, c.name
FROM members AS a
LEFT JOIN customvals AS b ON a.id = b.userid
LEFT JOIN customfields AS c ON b.rank = c.fieldid
WHERE a.Id = #MEMBERIDHERE#;

Related

The above query will not pull the information from the database

$read = "SELECT * FROM elmtree
WHERE id ='$getid' AND
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id";
The above query will not pull the information from the database to publish to the website.
Im trying to pull the item from the database with the $getid but also join the item id with the userid who uploaded it. Then using a while loop to print out the item to screen.
Any help would be greatly appreciated.
The SQL syntax you show isn't correct. A join clause describes which tables will be available for the rest of the query; all tables you mention need to be part of the ‘FROM’ clause, so that is where the ‘JOIN’ also belongs.
SELECT *
FROM elmtree
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id
WHERE id ='$getid'
Your SQL query was not correctly written. The AND is not used in joining tables and the WHERE statement should be after the JOIN.
Try the following:
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.id ='$getid'";
UPDATE
Could you try the following in your code (replacing $this->database with your database variable) and post the result:
if ($result = $conn->query($read)) {
while ($row = $result->fetch_assoc()) {
...
}
} else {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.itemid ='$getid'
Big thanks to Omari Celestine to finding the answer to the problem!

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

MYSQL query so it also returns values if has no value in the other table

Hi guys in the code below you can see what my JSON returns.
{"lifehacks":[{
"id":"2",
"URLtoImage":"http:\/\/images.visitcanberra.com.au\/images\/canberra_hero_image.jpg",
"title":"dit is nog een test",
"author":"1232123",
"score":"2",
"steps":"fdaddaadadafdaaddadaaddaadaaaaaaaaaaa","category":"Category_2"}]}
What the JSON returns is fine. The only problem is it is only displaying lifehacks if it has one like or more. So what should I change about my Query so it would display lifehacks without likes aswell.
//Select the Database
mysql_select_db("admin_nakeitez",$db);
//Replace * in the query with the column names.
$result = mysql_query("select idLifehack, urlToImage, title, Lifehack.Users_fbId, idLifehack, steps, Categorie, count(Lifehack_idLifehack) as likes from Lifehack, Likes where idLifehack = Lifehack_idLifehack AND idLifehack > " . $_GET["id"]. " group by idLifehack;", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['idLifehack'];
$row_array['URLtoImage'] = $row['urlToImage'];
$row_array['title'] = $row['title'];
$row_array['author'] = $row['Users_fbId'];
$row_array['score'] = $row['likes'];
$row_array['steps'] = $row['steps'];
$row_array['category'] = $row['Categorie'];
//push the values in the array
array_push($json_response,$row_array);
}
echo "{\"lifehacks\":";
echo json_encode($json_response);
echo "}";
//Close the database connection
fclose($db);
I hope my problem is clear like this. Thank you in advance I can't figure it out myself.
You need a LEFT JOIN here. Your query has an INNER JOIN.
select
idLifehack,
urlToImage,
title,
Lifehack.Users_fbId,
idLifehack,
steps,
Categorie,
count(Lifehack_idLifehack) as likes
from Lifehack
left join Likes on idLifehack = Lifehack_idLifehack
where idLifehack > whatever
group by idLifehack;
There's an excellent explanation of the different join types here.
A couple additional points...
Use prepared statements in your PHP. Your code is wide-open to SQL Injection, which has ruined careers and led to millions of innocent people having their personal information stolen. There are plenty of web sites showing how to do this so I won't go into it here, though I'll say my favorite is bobby-tables.
Avoid the implicit join anti-pattern in your queries. This is an implicit join:
FROM a, b
WHERE a.id = b.id
Use explicit joins instead; they separate your join logic from your filtering (WHERE) logic:
FROM a
INNER JOIN b ON a.id = b.id

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

Error handling in the following sql query

Fiddle with tables here
I'm using the following sql with the tables in the fiddle to check if a user has reached the borrowing limit. The problem here is, If an invalid item number were supplied it returns NULL, if a user has not borrowed any items, it returns NULL. This way, I cannot tell if a invalid item number were supplied or if a user actually has not borrowed any books. What would be a good way to check if a invalid item number was supplied or a member actually has not borrowed anything under that category?
set #mId = 3 //Has not borrowed anything till now.
set #id = 21; //This item does not appear in the collection_db table and is therefore invalid.
set #country = 'US';
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder and col1.country = lend.country
WHERE col1.id = #id and col1.country = #country
AND col2.category = 10
AND lend.memId = #mId and lend.country = #country
The furthest I could get with the one query is (had to take out php and "country" vars for fiddle to work):
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
,case when valid1.id is not null then 'true' else 'false' end as validId
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder,(
Select Distinct a.id From collection_db a
Where a.id = 4) valid1
WHERE col1.id = 4
AND col2.category = 10
AND lend.memId = 1
You may have to do a preparatory query checking for a valid memId:
$theQuery = "SELECT DISTINCT memId FROM lendings WHERE memId = 1"
Then test it here:
if (mysql_num_rows(mysql_query($theQuery)) <= 0) { /* No memId exists */ }
else { /* Do big query here */ }
You can use a tableA LEFT JOIN tableB, which will return results for the tableA even if tableB has no matches and will return NULL values for those in tableB.
Unfortunately, I can't quite figure out where you need LEFT JOINS, but probably you want them in both places.
You also might have to reorder the tables if it is the first table that should be on the right side of a LEFT JOIN. You could use a RIGHT JOIN but it is less readable to me.
maybe you should try "left join" if col1 do not have too much data,or do the query step by step

Categories