I want to delete the entire content of the subject in the database when its id is deleted.
if(isset($_GET['subject_id'])){
$subject_id = $_GET['subject_id'];}
$deleteexams = mysql_query("SELECT * FROM exam_exams where exam_subject_id = '$subject_id'")or die(mysql_query());
while($ids = mysql_fetch_array($deleteexams)){
$selected = $ids['exam_id'];
}
$deletequestions = mysql_query("SELECT * FROM exam_questions where question_exam_id = '$selected'")or die(mysql_query());
while($ids2 = mysql_fetch_array($deletequestions)){
$selectedids = $ids2['question_id'];
}
$deleteanswers = mysql_query("SELECT * FROM exam_answers where answer_question_set_id = '$selectedids'")or die(mysql_query());
while($ids3 = mysql_fetch_array($deleteanswers)){
$selectedidsans = $ids3['answer_id'];
}
/// I want to delete all of the answers inside the questions of the exams in the subject
mysql_query("DELETE * FROM exam_answers where answer_id = '$selectedidsans'")or die(mysql_error());
/////i want to delete all the questions
mysql_query("DELETE * FROM exam_questions where answer_id = '$selectedids'")or die(mysql_error());
////this will work because this has the subject ids
mysql_query("DELETE * FROM exam_exams where exam_subject_id = '$subject_id'")or die(mysql_error());
/////and this too
mysql_query("DELETE * FROM exam_subjects where subject_id = '$subject_id'")or die(mysql_error());
My problem is how can I delete the answers and questions because it has no subject_id on its fields.
Delete * from is not a correct syntax.
You do need to use IN as mentioned in the comment because then you can select all the answer_id s in the table using exam id, field names may change as per your situation but logic would be
DELETE
FROM exam_answers
WHERE answer_id IN
(SELECT answer_id
FROM questions
WHERE question_id IN
(SELECT exam_id
FROM exams
WHERE subject_id=<yoursubjectid>))
Not an efficient method, actually you may be better off storing subject id in each table even if it is redundant
Using IN with subquery would be my first option too but here are some others as well.
Are you using foreign keys in mysql tables? You could let mysql solve this for you via referential integrity and cascade.
Look here: MySQL foreign key constraints, cascade delete
If you are looking at PHP solution only you should first delete records from tables where you are using foreign keys.
E.g. first delete exams subject, questions and answers then delete the exam itself.
Another option would be not to delete records at all (if you need to have some sort of exam history). You could flag these records as deleted or unactive and filter them later when you select data from database.
Like this: SELECT * FROM exam_exams where active = 1;
Can you provide us with your mysql create table script or ERA diagram?
Related
In my database the Owning table has foreign key(Ownerid) which references the Owner id.After some steps I would like to delete all the Owner who's id isn't in the Owning table.
I have learnt how to delete with 'Delete' button a specific record but can't figure out how to delete more.This is my start:
$result = mysqli_query($link, "SELECT *
FROM Owner
WHERE Owner.id NOT IN (SELECT Ownerid FROM Owning )
");
while( $rowo = mysqli_fetch_array($result)):
/*TODO*/
endwhile;
$link is for the database connection
You only need one query for this, and no loops. You are so nearly there with your SELECT query.
Use this query to do the whole job:
$result = mysqli_query($link, 'DELETE FROM Owner WHERE id NOT IN (SELECT Ownerid FROM Owning)');
I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)
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 a table named users and has a user_id, and a table named groups and has a group_id and also have user_id that is a foreign key reference from users's user_id.The situation is here: if the user joined a group, his/her user_id is inserted into table groups. So if the user joined two different groups, the column 'user_id' in table 'groups' will insert two or more same user_id's. Well, I just want to bring the user_id once, either he/she joined two or more groups..
I have no idea how to loop it properly without getting user_id that is the same.... I just want it to loop once...
$query_groups = mysql_query("SELECT * FROM groups");
while ($rows_g = mysql_fetch_assoc($query_groups)) {
$g_user_id = $rows_g['user_id'];
$query_users = mysql_query("SELECT * FROM users WHERE user_id='$g_user_id'");
while ($rows_u = mysql_fetch_assoc($query_users)) {
echo $rows_u['user_id'];
}
}
change your code as follows:
$query_groups = mysql_query("SELECT user_id FROM groups LEFT JOIN users ON users.user_id = groups.user_id GROUP BY groups.user_id");
while($rows = mysql_fetch_assoc($query_groups))
{
echo $rows['user_id'];
}
You are using $rows_g but the variable is namend $rows in the first while loop.
Wrong:
$g_user_id = $rows_g['user_id'];
Correct:
$g_user_id = $rows['user_id'];
But try to use joining tables, because this is an inefficient way to get the wanted data.
In your case you should use LEFT JOIN.
I can't figure out why this statement is not working
$sql2 = mysql_query("
SELECT myChurches.id AS id, myChurches.church_name AS church_name
FROM myChurches
INNER JOIN church_staff
ON church_staff.church_id=myChurches.id
WHERE church_staff.mem_id='$logOptions_id'
ORDER BY myChurches.church_name
ASC
")
if(mysql_num_rows($sql2) > 0){
while($row2 = mysql_fetch_array($sql)){
$church_id = $row2['id'];
$church_name = $row2['church_name'];
$options .= '<option value="'.$church_id.'">'.$church_name.'</option>';
}
}
Basically I need to find the person's that are staff members of a church from one table and want to get the 'name' of that church FROM the 'myChurches' table. Hopefully that makes sense. Thanks in advance
EDIT:
Table 1 has a unique id and church_name
Table 2 has unique id, church_id, and mem_id
SELECT id, church_name
FROM myChurches
WHERE id = (SELECT church_id FROM church_staff WHERE mem_id = '$logOptions_id')
EDIT: this assumes that mem_id is unique as you said, but church_id should not be unique, unless you are doing something wrong (as it is a foreign key)
The problem was in the fetch array... The variable was different to the actual query variable. Thanks for the help