CodeIgniter Forums

Full Version: Delete from database ONLY if the uid from the database matches the uid in session
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My users can create a note that they can later delete, if they wish.

I'm storing the note in the database and these are my columns in my database: id, uid, note, time.

In my model (model_entry), I have this code to delete the note from database

PHP Code:
$this->db->where('pid'$pid);
 
       $this->db->delete('dayone_entries'); 

This, however, can let anyone delete any post id if they have the post id.

This is what I mean.

My view (view_all_entries):

PHP Code:
<a href="<?php echo base_url() . "profile/delete_entry/" . $data->pid; ?>">Delete</a

As you can see, it gets the pid and puts it in the website url and then moves it on to my controller.

My controller (profile.php) :

PHP Code:
function delete_entry() {
 
       $this->load->model('model_entry');
 
       $pid $this->uri->segment(3);
 
       $this->model_entry->entry_delete($pid);
 
       $this->entries();
 
   

And finally, my model which I have also written the code for above.

Model (model_entry):

PHP Code:
$this->db->where('pid'$pid);
 
       $this->db->delete('dayone_entries'); 

My question: I don't want anyone going in and deleting the notes. The person can only delete the note if IT BELONGS TO THEIR UID.

So if the pid is 3 and the uid is 1, only the user which has the uid 3 can delete the note (pid 3), no one else.
Hello,

Once user is logged in, you should store user id (In your case uid) in session.

And once user is pressing delete button which is having pid, should be checked with uid.

For setting uid in session:
$this->session->set_userdata('uid','userid');

For Delete use in model:

$this->db->where('pid', $pid);
$this->db->where('uid', $this->session->userdata('uid'));

Thanks & Regards
Tapan Thapa
Perfect solution, was planning to answer the same while reading post on homepage ^^

You just made a little mistake :

PHP Code:
$this->session->set_userdate('uid'$userid); 

Should be :

PHP Code:
$this->session->set_userdata('uid'$userid); 

And it's more secure (to me) to make a check before accessing a session var :

PHP Code:
if($this->session->userdata('uid') === false) {
    
// Throw error
} else {
    
$this->db->where('pid'$pid)
             ->
where('uid'$this->session->userdata('uid'))
             ->
delete('dayone_entries');