SQL inner join getting all data in column - php

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

Related

Showing two different values depending on SESSION value in INNER JOIN

I have two different tables, one named users, and another named transactions. Transactions contains wallet1, wallet2, amount. Users contains user details such as firstname, lastname, and wallet. I am trying to display the corresponding first name and last name, depending on whether or not the SESSION_wallet is equal to wallet1 or wallet2 within transactions. I tried searching for a while, and came up with a solution for showing the correct display name for the first and last name making the transfer, however, I am trying to make it display the correct value for "Transfer to:"
Here is some of my code to get a better understanding of what I mean:
MySQLi Query:
$result2 = mysqli_query($link, "SELECT * FROM transactions INNER JOIN users ON transactions.wallet1 = users.wallet WHERE transactions.wallet1 = '" . $_SESSION["wallet"] . "' OR transactions.wallet2 = '" . $_SESSION["wallet"] . "' Order by transactions.id DESC LIMIT 5 ");
PHP Code:
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
?>
The table that needs to display the transfer from, and transfer to:
<?php
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["firstname"]." ".$row["lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["firstname"]." ".$row["lastname"]."</td>";
}
?>
Right now my tables are only showing the first and last name of the user that made the Transfer, however, I need it to display the first and last name of the user that the transaction is made to as well. The else if code is working correct, but the first part is not showing the corresponding value.
You will need to JOIN your transactions table to your users table twice, once to get each users name. Then to avoid duplicate column names overwriting the results in the output array, you will need to use column aliases. Something like this should work:
$result2 = mysqli_query($link, "SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = '{$_SESSION["wallet"]}'
OR t.wallet2 = '{$_SESSION["wallet"]}'
ORDER BY t.id DESC
LIMIT 5 ");
Then you can access each user's names as $row['w1_firstname'] etc.:
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["w2_firstname"]." ".$row["w2_lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["w1_firstname"]." ".$row["w1_lastname"]."</td>";
}
Note that ideally you should use a prepared query for this, for example:
$stmt = $link->prepare("SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = ?
OR t.wallet2 = ?
ORDER BY t.id DESC
LIMIT 5");
$stmt->bind_param('ss', $_SESSION["wallet"], $_SESSION["wallet"]);
$stmt->execute();
$result2 = $stmt->get_result();

php mysql query combination

I first search all questions info. from "question" table including title, content, user etc.
the Code:
$sql = "select * FROM question where id>0 ORDER BY id ASC";
$result1 = mysql_query($sql);
$res=Array();
And then I want to search the user's point from "user" table. So I must search point for each user in each row from the result1
The Code:
while($rows=mysql_fetch_assoc($result1))
{
$res[]=$rows;
$user = $rows['user'];
$sql2 = "select point from user where name='$user'";
$result2 = mysql_query($sql2);
}
My problem is how to combine all the users' point(result2) with the questions info.(result1) together so that I can return a json for each row.
Use left join, as my understanding this work for you
$sql = "SELECT q.*, u.point AS point FROM question AS q LEFT JOIN user AS u ON q.user = u.name WHERE q.id > 0 ORDER BY q.id ASC";
$result = mysql_query($sql);
It's better go with the joins here i am giving you the query.i hope it may helps you
select * from question q,user u where q.id>0 ORDER BY id ASC
try something like this:using left join
select question.*,user.point FROM question left join user on user.name= question.name where id>0 ORDER BY id ASC

Combining Multiple MySQL JOIN Queries

I have this query which echos IDs of assignments for classes which users are enrolled in.
$sql = $db->prepare("SELECT assignments.*, enrollments.course_id, enrollments.student_id
FROM assignments
LEFT JOIN enrollments
ON assignments.course_id = enrollments.course_id
LEFT JOIN completed
ON assignments.id != completed.assignment_id
WHERE enrollments.student_id = ?
ORDER BY assignments.id DESC LIMIT 10
");
$sql->execute(array($login_id));
while($row = $sql->fetch())
{
echo $row['id'];
}
What would be the best way to do yet another check where I see if the assignment has been marked as completed?
This means that it would also need to check the "completed" table and make sure there is no row where the $login_id and assignment.id are present together for any of the assignments selected.
Here's a query I have right now to find completed assignment IDs for a user logged in.
$sqlcomplete = $db->prepare("SELECT * FROM completed
INNER JOIN students ON completed.student_id = students.id
WHERE completed.student_id = ?
");
$sqlcomplete->execute(array($login_id));
while($row = $sqlcomplete->fetch(PDO::FETCH_ASSOC))
{
echo "<li>You have completed assignment with ID ".$row['assignment_id']."</li>";
}
I've tried to do a more complex JOIN but I can't seem to figure it out. I also considered simply creating an array of the IDs of the assignments which the user has completed by querying that database alone, and throwing that ID into the while check, but I feel like that is not the best or most efficient solution.
You can use a LEFT JOIN and when completed.assignment_id IS NULL then that means there was no match returned from the completed table.
SELECT assignments.*, enrollments.course_id, enrollments.student_id
FROM assignments
LEFT JOIN enrollments ON assignments.course_id = enrollments.course_id
LEFT JOIN completed ON assignments.id = completed.assignment_id
WHERE enrollments.student_id = ?
AND completed.assignment_id IS NULL
ORDER BY assignments.id DESC LIMIT 10

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