Jump to content

Recommended Posts

Suppose that we have 3 related table in this manner in MySQL:

 

Table 1:

-------------

UserID

-------------

Username

-------------

Password

-------------

 

Table 2:

-------------

ProfileID

-------------

UserID

-------------

UserAvatar

-------------

 

Table 3:

-------------

ArticleID

-------------

UserID

-------------

Article

-------------

 

 

I need to delete every related records upon delete action on Table1. in other words, when user performs delete action on Table 1, related records from other related tables must be deleted automatically and not write tons of queries to achieve this or we have orphan records without its master record.

 

what should I do?

what are the best practices?

 

Thanks.

I would make a function and/or class, then call the function and/or class.

 

<?php
require_once 'link/to/db.php';
// if you don't connect to the db above, do it here
class db_procedures{
private $user_id = null;
public function __construct($user_id){
	$this->user_id = (int)$user_id;
}
public function delete_records(){
	$this->delete_from_1();
	$this->delete_from_2();
	$this->delete_from_3();
}
public function delete_from_1(){
	mysql_query("delete from table1 where UserID = $this->user_id");
}
public function delete_from_2(){
	mysql_query("delete from table2 where UserID = $this->user_id");
}
public function delete_from_3(){
	mysql_query("delete from table3 where UserID = $this->user_id");
}
}


$dbp = new db_procedures(12345); // Create instance of class and pass user id "12345"
$dbp->delete_records(); // Deletes records from table 1, 2, 3

// Or to delete just from table 2:
$dbp->delete_from_2();
?>

 

edit:

hmm... looks like may have I misunderstood the question, but the code above may help someone..

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.