SQL - Delete row based on number of rows in another table - php

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...

Related

Deleting multiple values in the database with their ids with different tables

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?

MYSQL get the name from another table that is associated with the first table

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

sql using LIKE clause : php

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.).

Add data to existing data in MySQL Database

I have a table called tblActivities. There are two fields ID and Attendees.
ID Attendees
1 Jon Jhonson
2 Ive Iveson
Which PHP function or MySQL statement do I need to use to get to this result:
ID Attendees
1 Jon Jhonson, Ive Iveson, Adam Adamer
2 Ive Iveson
In other words, how can I add new data to existing data in my database?
You need something like:
UPDATE tblActivities
SET Attendees = CONCAT(Attendees, "Ive Iveson, Adam Adamer")
WHERE id = 1;
But maybe you should change the database layout. It is preferable to have only one value in one field. You could find more information under http://en.wikipedia.org/wiki/Database_normalization.
use mysql's update statement. If you want to exeute through php then
first get the existing value using select statement,
SELECT Attendees from <table-name> WHERE ID = 1
you will get attendees existing value, put it in a php variable, now concatenate your value..
and then update,
UPDATE <table_name>
SET Attendees=<new-value>
WHERE ID=1
you would have to use the php's mysql functions to run the above queries
I think you're better off restructuring. Make a table:
ID (primary key)
ACTIVITY_ID (foreign key to activity table)
ATTENDEE (foreign key to USERS table)
Then select everything from that event and concat in PHP.
$q = mysql_query( 'SELECT ATTENDEE FROM tblActivities '.
'WHERE ACTIVITY_ID = $activity_id' );
$attendees = array();
while( $row = mysql_fetch_assoc( $q ) )
{
$attendees[] = $row['attendee'];
}
$attendees =implode( ' ', $attendees );

PHP/ MYSQL Inserting Data Into Multiple Tables

I am trying to add data into 3 table using PHP, atm I can only view the results of the tables that are joined .
RESULTS QUERY
$sql = mysql_query("SELECT PART_ID, PART_DESC, SERIAL_NUM, PART.RACK_NUM, PART.PART_TYPE_ID, PART_TYPE_DESC, LOCATION
FROM PART
INNER JOIN PART_TYPE ON PART.PART_TYPE_ID = PART_TYPE.PART_TYPE_ID
INNER JOIN RACK ON RACK.RACK_NUM = PART.RACK_NUM
This will get all the rows from the PART table, and for each of the rows we find, match that row to a row in the PART_TYPE table (the condition being that they have the same PART_TYPE_ID). If no match between the PART and PART_TYPE tables can be found for a given row in the PART table, that row will not be included in the result.
My Insert Query This is where im having trouble
How do I add the data to the PART_ID, PART_TYPE and RACK tables?
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['PART_ID'])) {
$id = mysql_real_escape_string($_POST['PART_ID']);
$PART_DESC = mysql_real_escape_string($_POST['PART_DESC']);
$SERIAL_NUM = mysql_real_escape_string($_POST['SERIAL_NUM']);
$RACK_NUM = mysql_real_escape_string($_POST['RACK_NUM']);
$PART_TYPE_ID = mysql_real_escape_string($_POST['PART_TYPE_ID']);
$LOCATION = mysql_real_escape_string($_POST['LOCATION']);
$PART_TYPE_DESC = mysql_real_escape_string($_POST['PART_TYPE_DESC']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT PART_ID FROM PART WHERE PART_ID='$id' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
**$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());**
header("location: inventory_list.php");
exit();
}
?>
Micheal if I understood your problem you just need to do 2 other SQL INSERT to add data in the other table
$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());
$currentID = mysql_inserted_id();
$sql2 = mysql_query("INSERT INTO PART_TYPE [..]");
$sql3 = mysql_query("INSERT INTO RACK [..]");
You can use $currentID if you need the ID of the last record inersted into PART
But still I strongly suggest you to learn PDO http://php.net/pdo for sql
your table management is wrong, you never use arrows just to show that you are joining it with that table from this table, but rather from the key in first table to foreign key in the second table, that's what i would start from, maybe a better idea would be to join them using JOIN look up in google how joins are working, that may be the cause...
I agree with #yes123, that is the correct way to insert into tables, if you have a program called heidisql then use it, because there is a window to run your queries... that way to test if it is properly written also use mysql_error.
Debug, debug, and one more time debug your code.
Your tables are not correctly designed.
Try this table structures .
In your base table Part. -
The columns in this should be:
Part_id
part_desc
serial_num
The part_type should have following columns:
part_type_id
part_type_desc
part_id -> foreign key to the parent table
The rack table should be:
Rack_num
location
part_id -> foreign key to the parent table.
So your select query to get all the part related information would be:
$sql="select * from part join part_type pt on tp.part_id=part.part_id join Rack_num rn on rn.part_id=part.part_id";
With this structure the data remains normalized. And is flexible, so if the parts are on multiple racks you just go to the rack table and add and new rack number and the part id.

Categories