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
Related
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();
For this problem I need to make a PHP page where the user can search an invoice table by inputting a "quantity" value. The form then takes that quantity and spits out a table with the name, invoice number, quantity, and item description for all invoices where the quantity exceeds the quantity the user submitted.
For the most part I have my page set up and working fine. Where I'm getting stuck is on the query side -- specifically, the code below is providing me a list of invoices where the quantity is identical to the input quantity.
I've tried changing "WHERE ii.quantity LIKE ?" to "WHERE ii.quantity > ?" but all that does is provide me a list of all invoices without filtering by the user submitted quantity.
$query =
"SELECT c.first_name, c.last_name, ii.invoice_id, ii.quantity, it.description
FROM `c2092`.`customer` c
JOIN `c2092`.`invoice` i ON c.customer_id = i.customer_id
JOIN `c2092`.`invoice_item` ii ON ii.invoice_id = i.invoice_id
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity LIKE ?
ORDER BY ii.invoice_id";
This is too complex query. Try to make explain on it. I am sure it will use filesort, and even temp table.
The better approach is to make several queries:
$invoiceItems = $db->query(
"SELECT ii.invoice_id, ii.id, ii.quantity, it.description
FROM `c2092`.`invoice_item` ii
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity > ?
ORDER BY ii.invoice_id");
$invoiceItemMap = [];
$invoiceIds = [];
foreach ($invoiceItems as $invoiceItem) {
$invoiceItemMap[$invoiceItem['invoice_id']][] = $invoiceItem;
$invoiceIds[$invoiceItem['invoice_id']] = $invoiceItem['invoice_id'];
}
$invoiceIds = array_values($invoiceIds);
$userInvoices = $db->query(
"SELECT c.first_name, c.last_name, i.invoice_id
FROM `c2092`.`invoice` i
JOIN `c2092`.`customer` c ON c.customer_id = i.customer_id
WHERE i.id IN (".implode(',', $invoiceIds).")");
$result = [];
foreach ($userInvoices as $row) {
$result[] = array_merge($row, $invoiceIds[$row['invoice_id']]);
}
Hello,
What is the value of your variable?
Prefer the use of named parameter instead of ? syntax.
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;
}
}
Here is my code:
<?php
$data = mysql_query("SELECT * FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
if(!empty($info['user'])){
Print "".$info['user'].""; }
else {
}
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result3 = mysql_query("SELECT COUNT(source_user_id) FROM likes
INNER JOIN pins ON pins.id = likes.pin_id
WHERE pins.board_id='$id'");
$c = mysql_result($result3, 0); // Cumulative tally of likes for board
{
Print "$c";
}
}
?>
The first part gets a users name and board details (board as in a photo album).
the second part joins that data with another sql table that counts the number of likes that board has.
Both are displayed as a name and a score represented by a number.
By default they are ordered by the date of creation. I'd like to be able to order them by the score. However, since the score is determined in the second part of the code, I don't know how to achieve it. Is it possible?
The solution is of course to query both at once in the first place, via a LEFT JOIN against a subquery returning the count per board_id:
SELECT
board.*,
/* Your PHP code will retrieve the likes count via this alias `numlikes` as in $info['numlikes'] */
numlikes
FROM
board
LEFT JOIN (
/* Subquery returns count per board_id */
SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM
likes
INNER JOIN pins ON pins.id = likes.pin_id
GROUP BY pins.board_id
) likes ON board.id = likes.board_id
ORDER BY numlikes
It is nearly always significantly more efficient to perform a single query rather than n queries in a loop. You should strive to do so whenever possible.
You can do it in one query
SELECT board.*, count(likes.source_user_id) as score
FROM board
INNER JOIN pins
ON pins.board_id = board.id
INNER JOIN likes
ON pins.id = likes.pin_id
ORDER BY score
i am having trouble creating a single mysql query for what i am trying to do here.
first off, i will show you the table structures and fields of the tables i am using for this particular query:
users:
- id
- name
- photo_name
- photo_ext
user_attacks:
- id
- level
user_news_feed:
- id
- id_user
- id_status
- id_attack
- id_profile
- id_wall
- the_date
user_status:
- id
- status
user_wall:
- id
- id_user
- id_poster
- post
whenever the user posts an attack, or status update, updates their profile, or posts on someones wall, it inserts the relevant data into its respective table and also inserts a new row into the user_news_feed table.
now, what i want to do is select the last 10 news feed items from the database. these news feed items need to grab relevant data from other tables as long as their value is not 0. so if the news feed is for a status update, the id_status would be the id of the status update in the user_status table, and the "status" would be the data needing to be selected via a left join. hope that makes sense.
heres my first mysql query:
$sql = mysql_query("select n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date, u.id, u.name, u.photo_name, u.photo_ext, s.status
from `user_news_feed` as n
left join `users` u on (u.id = n.id_user)
left join `user_status` s on (s.id = n.id_status)
where n.id_user='".$_GET['id']."'
order by n.id desc
limit 10
");
now this works great, except for 1 problem. as you can see the user_wall table contains the id's for 2 different users. id_user is the user id the post is being made for, and id_poster is the user id of the person making that wall post. if the user makes a wall post on his/her own wall, it is inserted into the database as a status update into the user_status table instead.
so i have a conditional statement within the while loop for the first query, which has another sql query within it. here is the whole code for the while loop and second sql query:
while ($row = mysql_fetch_assoc($sql))
{
if ($row['id_wall'] != 0)
{
$sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post
from `user_wall` as w
left join `users` u on (u.id = w.id_poster)
where w.id='".$row['id_wall']."'
");
while ($row_u = mysql_fetch_assoc($sql_u))
{
$row['photo_name'] = $row_u['photo_name'];
$row['photo_ext'] = $row_u['photo_ext'];
$row['id_user'] = $row_u['id'];
$row['name'] = $row_u['name'];
$content = $row_u['post'];
}
}
else
{
if ($row['id_status'] != 0)
$content = $row['status'];
else if ($row['id_attack'] != 0)
$content = '<i>Had an attack</i>';
else if ($row['id_profile'] != 0)
$content = '<i>Updated profile</i>';
}
echo '<li'.(($count == $total_count) ? ' class="last"' : '').'>';
echo '<img src="images/profile/'.$row['photo_name'].'_thumb.'.$row['photo_ext'].'" alt="" />';
echo '<div class="content">';
echo '<b>'.$row['name'].'</b>';
echo '<span>'.$content.'</span>';
echo '<small>'.date('F j, Y \a\t g:ia', $row['the_date']).'</small>';
echo '</div>';
echo '<div style="clear: both;"></div>';
echo '</li>';
}
i hope what i am trying to do here makes sense. so basically i want to have both sql queries ($sql, and $sql_u) combined into a single query so i do not have to query the database every single time when the user_news_feed item is a wall post.
any help would be greatly appreciated and i apologise if this is confusing.
SELECT n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date,
u.id, u.name, u.photo_name, u.photo_ext, s.status,
w.id AS wall_user_id, w.name AS wall_user_name,
w.photo_name AS wall_user_photo_name,
w.photo_ext AS wall_user_photo_ext,
w.post
FROM user_news_feed AS n
LEFT JOIN users AS u ON (u.id = n.id_user)
LEFT JOIN user_status s ON (s.id = n.id_status)
LEFT JOIN (SELECT a.id AS id_wall, b.id, b.name, b.photo_name, b.photo_ext, a.post
FROM user_wall AS a
LEFT JOIN users AS b ON (b.id = a.id_poster)
) AS w ON w.id_wall = n.id_wall
WHERE n.id_user = ?
ORDER BY n.id desc
LIMIT 10
The '?' is a placeholder where you can provide the value of $_GET['id'].
Basically, this adds an extra outer join, to the main query (and some extra columns, which will be NULL if the news feed event is not a wall posting), but the outer join is itself the result of an outer join.
Back again ;)
Anyway, forget about merging the queries in my opinion.
What you should do instead is to do the first query, loop through all the results and store all "id_wall"s in a separate array... then rather than doing a separate query per "id_wall" you do this:
$wallids = array();
while ($row = mysql_fetch_assoc($sql))
{
$wallids[] = $row['id_wall'];
// also store the row wherever you want
}
$sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post
from `user_wall` as w
left join `users` u on (u.id = w.id_poster)
where w.id IN ('".implode(',', $wallids) ."')
");
$wallids being an array with all the "id_wall"s. So now you have a total of 2 queries.