Getting relational table data - php

I have the following tables:
member
id, firstName, lastName
team
id, name
teamMember
id, teamId, memberId
I am trying to access the relational table so I can output the members firstName and Lastname:
$sql = "SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
JOIN team
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND team.id = 1";
I have set a hard value in the team.id so I can test to make sure it returns the members of team 1 for now.
so the end goal here is that I need to access the relational table to give me back the names of members that are associated to the team id set in the select query by ID.
I am struggling to get the output need.
And return the values like so:
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "{$row['firstName']} {$row['lastName']}<br>";
}
}
The error I am seeing is:
Notice: Trying to get property of non-object in
Which refers to: if ($result->num_rows > 0) {
The output I want to see is the members firstName and lastName from the member table

You are probably want all the results or rows associated to the desired team id. But, Using a INNER JOIN you would only get a single row for one team because that is how JOIN works.
Instead you should use a query like this :
SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND teamMember.teamId = 1"
Hope this would work.
However, As of bool(false), your query was also broken and would not get you desired results.
In your query you have joined three tables and defined the condition for only one. This would be what your query should look like
"SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
JOIN team
ON teamMember.teamId= team.id
WHERE dashboardId = 1 AND team.id = 1";

Related

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

SQL inner join getting all data in column

This is my first time using an inner join so i'm very confused.
I have two tables.
This is my first table called members
This is my other table called donations. The userID from the members is linked up with the userID on the donations table.
Right so what i'm trying to do is select all of the data from members and from the donations table and assiotate each Id with the donation amount. So what i'm trying to do is echo all of the names along side their donation amount if that makes sense.
This is my code at the moment
$connect - contains my config
//Connection info.
global $connect;
//inner join
$sql = "SELECT members.firstname, members.lastname
FROM members INNER JOIN donations ON members.userID = donations.userID WHERE donations.amount !='' ORDER BY members.userID ASC ";
$result = mysqli_query( $connect, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$list .= $row["firstname"];
echo $list;
}
I'm getting this error back: mysqli_fetch_array() expects parameter 1 to be mysqli_result boolean
UPDATE: Thanks for all your help, i'm running the SQL query and just getting the first and last name back.
SELECT members.firstname, members.lastname FROM members INNER JOIN donations ON members.userID = donations.userID WHERE donations.amount !='' ORDER BY members.userID ASC
I think i'm doing something wrong here !='' the donation amount is a decimal am i targeting it right?
You have typo in column name 'fisrname' => 'firstname'.
Check the query first in phpmyadmin or the other tool.
Also read about mysqli_error and later about other means of accessing the DB (like PDO, Doctrine etc.).
Replace members.id by members.userID in your query.
SELECT members.firstname, members.lastname, donations.amount
FROM members
INNER JOIN donations ON members.userID = donations.userID
WHERE donations.amount != ''
ORDER BY members.userID ASC
As for the SQL error, it's because $result is false when there's a problem with the query or no result has been found.
mysqli_fetch_array() expects parameter 1 to be mysqli_result boolean
To prevent the error, add a simple if case because your while.
if($result){
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$list .= $row["firstname"];
echo $list;
}
}

mysql return the total of rows for each user_id

$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)

SQL ERROR When i join 2 tables

Sorry let me revise. I have a three tables:
events_year
• EventID
• YearID
• id
Date
• YearID
• Year
Event
• EventID
• EventName
• EventType
i want to dispay a record from the three tables like so:
EventName - Year: Marathon - 2008
i linked it to a table called "members" which contains a ID number field (members-id)
so i can limit the results to members id = $un(which is a username from a session)
I need to join the three tables and limit the results to the specific ID number record
Here is my portion of the code:
$query = "SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
"SELECT * FROM Event JOIN events_year ON Event.EventID = events_year.EventID WHERE username = '$un'";
"SELECT * FROM Date JOIN events_year ON Date.YearID = events_year.YearID WHERE username = '$un'";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo $row['Year'];
echo " - ";
echo $row['Event'];
echo "<br>";
}
the notices are almost self-explaining. There are no 'Year' and 'EventName' fields in the resultset. It's difficult (or: impossible) to tell why this happens as you haven't given your table-structure, but i guess this: 'Year' is a field of the date-table, 'EventName' is a field of the event-table - you're only selecting from members so this fields don't occur.
I don't understand why there are three sql-statements but only one is assigned to a variable - the other two are just standing there and do nothing. Please explain this and put more information into your question about what you're trying to achive, what your table-structure looks like and whats your expected result.
I think what you really wanted to do is some kind of joined query, so please take a look at the documentation to see how this works.
finally, i think your query should look like this:
SELECT
*
FROM
members
INNER JOIN
events_year ON members.id = events_year.id
INNER JOIN
Event ON Event.EventID = events_year.EventID
INNER JOIN
´Date´ ON ´Date´.YearID = events_year.YearID
WHERE
members.username = '$un'
Does the field 'Year' exist in the query output ? I suspect not.
the string $query is only using the first line of text:
"SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
and not the others.
The query itself is not returning any fields that are called Year or EventName.
Do a var_dump($row) to find out what is being returned.

Extracting member's first name from member table using results from another table

<?php
include 'dbFunctions.php';
$courseid = $_GET['Course_id'];
$query = "SELECT * FROM course WHERE Course_id=".$courseid."";
$arrCourse = executeSelectQuery($query);
$query2 = "SELECT * FROM course_member WHERE Course_id=".$courseid."";
$result = mysqli_query($link,$query2) or die(mysqli_error($link));
?>
HTML body:
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<?php echo $row['member_id']
?>
<?php
}
?>
this correctly prints the results of the member id that is involved in the selected course, however, i want to extract the first_name using the result generated that belong to another table called member.
been trying all the join queries but it didn't work.
Sounds like you need to read up on the JOIN operation in SQL. The following query will return all the data you seem to need, from a single query:
SELECT *
FROM course
INNER JOIN course_member ON course.id = course_member.course_id
INNER JOIN member ON member.id = course_member.member_id
As far as I see
$sql="select last_name from course_member
join member on course_member.member_id = member.member_id
where course_member.Course_id = ".$courseid;
I'm going to take a guess here at your table defs...
$query2 = "SELECT m.first_name, cm.* FROM course_member cm join member m on m.id = cm.member_id WHERE Course_id=".$courseid."";
If you want only the member name and you are not much interested with the id then you can merge it into a single query
$query = SELECT fName from member WHERE id = (SELECT member_id FROM course_member WHERE Course_id=$courseid);

Categories