I'm using CODEIGNITER framework.
My situation is this. I have a list of data. The user selects which record to delete (through checkboxes). I have to do it in ajax because my client doesn't want to see the system refreshing. I've successfully transferred the data through JSON.
Now, my problem is, in the server side, I don't know how to populate the array with the dynamic record (the array is what I will use to delete the records in the database).
I have a solution but I'm not sure if this is a good programming practice.

My solution is this:
delete the records one by one with a loop.
I think it's inefficient but what do you guys think? Please give me a strategy.

Recommended Answers

All 8 Replies

If you have a list of ID's then you can do a query like this:

DELETE FROM `table` WHERE `id` IN (1, 2, 4, 5, 6)

Just explode your array to build the where block.

^^ Sorry.. I'm not familiar with that code so I don't know what those numbers are for.

PS, I don't know how many records will be checked.

If you show how the array looks you are getting, I'll show you how to build that query in code.

the array is just a list of integers (IDs of the records the user wants to delete). I don't know how many.
I've used JSON to put it in. so it can be accessible by:
$field->myArr[index]->jobs;

The javascript code wherein IDs are placed in the JSON object

function deleteJobs()
{
    var conf = confirm("Are you sure?");
		
    if(conf == true){
	var jobz = document.getElementsByName("jobz");
			
	var obj = {
	  jobs: [],
	  length: jobz.length,
	  "mode" : "deleteJob"
       };

      for(var i = 0; i < jobz.length; i++) {
	if(jobz[i].checked == true){
	  obj.jobs.push({ 
	    "jobz" : jobz[i].value
	  });
        }
     }
			
   ajx(obj, "deleteJob");
   }
		
	return false;
}

Then the part where stringified JSON object is decoded

function transact()
{
    if(isset($_GET['json'])){
    $field = json_decode($_GET['json']);
    }
    if($field->mode == "deleteJob")
    {
      $this->load->model('Job');
      $this->Job->remove($field);
    }

}

Then the delete code.

function remove($field)
{	
    for($i = 0; $i < $field->length; $i++)
    {
	$this->db->or_where_in('jobid', $field->jobs[$i]->jobz);
	$this->db->delete('jobs');
    }
	
    //echo "Delete Successful!";
}

the delete code works but I'm not sure if it's efficient especially if say, the user is deleting 100 records.

See the code igniter manual if or_where_in can accept an array. If it does, you could pass all your id's at once.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.