I have a table which holds details of exams taken. Each exam entered into this table is entered as a pair of people i.e. two people per exam performed so you have per exam, two people. Each person has their own unique id for each exam taken but each pair has a value called partner_id which is the same for them both.
What I am trying to do is extract the partner_id values from that table in order to then be able to use those values to find the partners of a said person and show/echo onto the page the exam result details of every partner that person has had exam with.
What I have tried so far is:
$partner_ider = mysql_query("SELECT partner_id as value1 from exam WHERE Student_email='eating#gnomes.com'");
$row1 = mysql_fetch_array($partner_ider);
while($row1 = mysql_fetch_array($partner_ider))
{
echo $row1['value1'];
}
And this:
$result = mysql_query("SELECT * from exam WHERE Student_email='beating#dead.com'");
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result))
{
echo $row['partner_id'];
}
The result these would give is 2 for that email of which has two entries in the exam table, what I was looking for was 1, 2 which are the values of the two partner_ids for this email's exam records. When I change the email to someone else who only has one, it returns nothing.
What I would be looking to do with the result of 1, 2 is to use those values to select all other people except the original person(eating#gnomes.com) and show their details from out of that table.
What I'm asking for is how would I go about doing the above as I haven't done something like this before?
In both code snippets, you have at line 2 a mysql_fetch_array() which should not be there.
It fetches a row, puts it into $row1 and increments the internal pointer.
When you call mysql_fetch_array() in your while, it fetches the second record then the third etc. until all the rows have been processed.
You should, in both examples, remove the second line and try again.
$partner_ider = mysql_query("SELECT partner_id as value1 from exam WHERE Student_email='eating#gnomes.com'");
//$row1 = mysql_fetch_array($partner_ider);
while($row1 = mysql_fetch_array($partner_ider))
{
echo $row1['value1'];
}
If your table structure is the following :
id
student_id
student_name
student_email
student_whatever
partner_id
The SQL query would look like
SELECT Student_email FROM exam WHERE partner_id IN (SELECT partner_id FROM exam WHERE student_Email = 'eating#gnomes.com') AND Student_email <> 'eating#gnomes.com';
But you should really split up your table. You have two entities (a student and an exam) and a joining table.
Student
id
name
email
Exam
id
name
(other exam data)
StudentGroup
exam_id
student_id
group
Related
How would I go about deleting a row from the table 'subjects' that has a primary id 'subject_id' based on the number of rows in another table named 'replies' that uses a 'subject_id' column as a reference.
Example in pseudo code:
If ('subject' has less than 1 reply){
delete 'subject'}
I don't know much about SQL triggers so I have no clue if I would be able to incorporate this directly in the database or if I'd have to write some PHP code to handle this...
To delete any subjects that have had no replies, this query should do the trick:
DELETE s.* FROM subjects AS s
WHERE NOT EXISTS
(
SELECT r.subject_id
FROM replies AS r
WHERE r.subject_id = s.subject_id
);
Demo: DB Fiddle Example
One of the MySQL gurus will need to weigh in on whether or not you can do this directly, but in PHP you could...
$query = "SELECT subject_id FROM subjects WHERE subject='test'";
$return = mysqli_query($mysqli, $query);
$id = mysqli_fetch_assoc($return);
$query = "SELECT reply_id FROM replies WHERE subject_id='".$id[0]."'";
$return = mysqli_query($mysqli, $query);
if(mysqli_num_rows($return) < 1){
$query = "DELETE FROM subjects WHERE subject_id='1'";
$return = mysqli_query($mysqli, $query);
}
This example assumes the "subject" is unique. In other words, SELECTing WHERE subject='test' will only ever return one subject_id. If you were doing this as a periodic cleaning, you would grab all the subject_id values (no WHERE clause) and loop through them to remove them if no replies.
You can achieve this in one query by selecting all (unique) subject-ids from the replies table, and delete all subjects that doesn't have a reply in there. Using SELECT DISTINCT, you don't get the IDs more than once (if a subject has more than one reply), so you don't get unnecessary data.
DELETE FROM subjects
WHERE subject_id NOT IN (SELECT DISTINCT subject_id FROM replies)
Any subject that doesn't have a reply should be deleted!
So you want to delete all subjects with no replies:
DELETE FROM subjects WHERE subject_id NOT IN
(SELECT subject_id FROM replies);
I think this is what you want...
I have this simple query:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a many to many relationship. It is used as a lookup table. Each userid can be associated with multiple listingids and vice versa.
Also in my file (a html template file) I have this code
if(!empty($_SESSION[UserID]) and $a5['listingid'] == $_GET['id']) :
So I am wanting to check if the listingid column in userlisting table = the id of the page (well, it is a property website and it is the id of the property). As each user can be associated with many listingids I need to be able to check multiple rows. But for some reason it only checks the very first row.
In the userlisting table there is the following test entries:
userid | listingid
1 1
1 2
So one user associated to two listingids. However, it is acting like this userid is only associated with listingid 1, the very first row.
You are only grabbing the first entry.
$a5 = mysql_fetch_array($r5);
This does not fetch the whole query result, but only the first row. If there is none, it will return false.
You have to create a loop to get more results.
I have two tables:
Table 1: Articles (id, name, title, content)
Table 2: Comments (id, comment, a_id)
Table 2 contains comments with a_id corresponding with the id field in Table 1, and has several rows for the same article
I used the following select statement:
$result = mysql_query("SELECT * FROM articles a JOIN comments c ON a.id = c.a_id WHERE a.name='$a'");
$row = mysql_fetch_array($result);
echo $row["title"]."<br/>".$row["content"]."<hr/>".$row["comments"]
Security issues aside, this shows the contents for the given article name $a, but gives only one comment when there should be multiple ones. What must I do to get all comments for the given article to show up? And shouldn't $row["comments"] be an array?
The end result I'm going for is displaying one article at a time, and all the comments assigned to the given article. Currently all I'm getting is one article and one (the first) comment, even though there are multiple rows in Table 2 with the same value for the a_id field
You have to put your fetch in a while loop:
$i=0;
while($row = mysql_fetch_assoc($result))
{
if(!$i)
{
echo $row["title"]."<br/>".$row["content"]."<hr/>";
$i++;
}
echo $row["comment"] . "<hr />";
}
I have a table called "profiles". There was a column in this table called "user_id" which I have changed the name to "username" and the type from INT(11) to Varchar(255) . However the contents of this column are still numeric ids.
These ids correspond to another table called "users". That table has fields called "user_id" and "username". For each row on the "profiles" table I need to first check to see what the username field has for the id and do a look up on the users table to get the username that correcponds to that id and then update the profile table's username value for with the proper username.
Profiles table:
username | blah blah...
------------------------
1 | ...
Users table:
user_id | username
------------------------
1 | Joe
I need the value for the username field on the profiles table to be updated to "Joe".
I came up with this php script but it stops working after updating just 4 records for some reason:
$sql = 'SELECT username FROM profiles';
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$id = $row['username'];
$sql = 'SELECT username FROM users WHERE user_id = '. $id;
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$sql = "UPDATE profiles SET username = '".$row['username']."' WHERE username = $id";
$query = mysql_query($sql);
if(!$query) {
echo 'error!';
}
}
}
My script isn't all that efficient to begin with, although that's not that big an issue since the table has just 50k records. Anyway what would be a way to do this directly from mysql?
You are manipulating the $row variable inside the first loop. Obviously it does not work. Try giving the variable in inner loop a different name.
And not only that almost all the variables you are using, outside the first loop, you are using the same names inside the inner loop.
Also coming to db schema I would prefer ids to be foreign keys not usernames because querying using ids would be faster than with columns of type varchar.
One more suggestion is that there is no need to use
while($row = mysql_fetch_assoc($query))
because there would be only one row
As Napster said you're overwriting your $query, and $row variables. That should fix your immediate issue.
Additionally, a query inside of a while loop, inside of a while loop is absolutely terrible. No offense intended! We all have to start somewhere. But I would strongly look into how you can rewrite this with a JOIN just so you have something in your toolbelt for that next time.
Hope that helps!
I think relationship between your tables is wrong, you should have a foreign key in profiles table that links to user_id in the users table, then if you change something like Joe to Michael, its corresponding record in profiles table will be updated.
Profiles table:
user_id | blah blah...
------------------------
1 | ...
Users table:
user_id | username
------------------------
1 | Joe
You can do this in one query
UPDATE profiles t1
INNER JOIN users t2 ON t1.username=t2.user_id
SET t1.username=t2.username
Why you would want to do this is another question.
I'm trying to generate a list of events that a user is attending. All I'm trying to do is search through columns and comparing the userid to the names stored in each column using LIKE.
Right now I have two different events stored in my database for testing, each with a unique eventID. The userid i'm signed in with is attending both of these events, however it's only displaying the eventID1 twice instead of eventID1 and eventID2.
The usernames are stored in a column called acceptedInvites separated by "~". So right now it shows "1~2" for the userid's attending. Can I just use %like% to pull these events?
$userid = $_SESSION['userid'];
echo "<h2>My Events</h2>";
$myEvents = mysql_query("select eventID from events where acceptedInvites LIKE '%$userid%' ");
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
My output is just 11 when it should be 12
Change your table setup, into a many-to-many setup (many users can attend one event, and one user can attend many events):
users
- id (pk, ai)
- name
- embarrassing_personal_habits
events
- id (pk, ai)
- location
- start_time
users_to_events
- user_id ]-|
|- Joint pk
- event id ]-|
Now you just use joins:
SELECT u.*
FROM users u
JOIN users_to_events u2e
ON u.id = u2e.id
JOIN events e
ON u2e.event_id = e.id
WHERE u.id = 11
I'm a bit confused by your description, but I think the issue is that mysql_fetch_array just returns one row at a time and your code is currently set up in a way that seems to assume $fetch is filled with an array of all the results. You need to continuously be calling mysql_fetch_array for that to happen.
Instead of
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
You could have
while ($row = mysql_fetch_array($myEvents)) {
echo $row['eventID'];
}
This would cycle through the various rows of events in the table.
Instead of using foreach(), use while() like this:
$myEvents = mysql_query("SELECT `eventID` FROM `events` WHERE `acceptedInvites` LIKE '".$userid."'");
while ($fetch = mysql_fetch_array($myEvents))
{
echo $fetch['eventID'];
}
It will create a loop like foreach() but simpler...
P.S. When you make a MySQL Query, use backticks [ ` ] to ensure that the string is not confused with MySQL functions (LIKE,SELECT, etc.).