I have 2 tables.
contacts and complaints.
contacts has 3 columns:
contact_id, contact_name, score
complaints has 4 columns:
complaint_id, contact_id, score_deduction, complaint_type
I am able to obtain value $_GET['complaint_id'] from previous page.
What i am trying to do is delete the record with that particular complaint_id and get the value of complaints.score_deduction and add it back to contacts.score.
I have spent hours and cant seem to figure it out.
Please help.
if (isset($_GET['complaint_id'])) {
record_set('complaints',"SELECT * FROM add_complaints WHERE complaint_id = ".$_GET['complaint_id']."");
$contact_id = $row_complaints['contact_id'];
record_set('contact',"SELECT * FROM contacts WHERE contact_id = $contact_id");
$score = $row_contact['contact_score'];
echo $score;
}
You can just combine that into a single query.
SELECT * FROM add_complaints AS ac
INNER JOIN contacts AS c on ac.contact_id = c.contact_id
WHERE ac.complaint_id = ?
I am not familiar with whatever you are using to make the DB queries. But I assume you would know how to get the contact id, current score, and score deduction values. And make the update query and delete queries from there.
IF you wanted to get more fancy and just update the contact record in place without needing to select anything you could also do:
UPDATE add_complaints AS ac
INNER JOIN contacts AS c on ac.contact_id = c.contact_id
SET c.score = c.score - ac.score_deduction
WHERE ac.complaint_id = ?
Then just delete the complaint
DELETE FROM add_complaints WHERE complaint_id = ?
Related
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
I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos 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.
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.
Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1