0

I have an array that looks like this:

[0] => Array
    (
        [image] => http://images0.jpg
        [title] => 
    )

[1] => Array
    (
        [image] => http://image1.jpg
        [title] => 
    )

[2] => Array
    (
        [image] => http://image2.jpg
        [title] => 
    )

And I save this array to database with saveAll, and when I unset for example key 2 from this array how to delete the corresponding record from the database which is not set?

2
  • I wouldn't recommend this method for removing items from a database. Otherwise if you look for what's "not" in the array, you'll end up deleting all the rows! Commented Jan 14, 2011 at 13:43
  • So what is the best method? I want to compare the existing items with array and remove elements that doesnt exist. Im out of ideas. Can you give me some? Commented Jan 14, 2011 at 14:53

1 Answer 1

1

I would do it this way:

add in the form extra field type of checkbox, you can add some javascript for better user experience.

the code could be something like this:

foreach($files as $key=>$file){
   echo '<div class="file" id="file_'.$key.'">';
   $this->Form->input("$key.title");
   $this->Form->input("$key.image");
   $this->Form->input("$key.deleted", array('type'=>'checkbox'));
   echo '</div>';
}

When the user click on the checkbox, a warning "Are you sure" can appear, and if the user click "Yes", then the surrounding div#file_XXX could be set to hidden.

This basically will hide the div, but the fields will be present when the user submits the form.

Then you can save the data with saveAll(), and later on delete the records which has deleted=1.

Basically your array will look like this:

[0] => Array
    (
        [image] => http://images0.jpg
        [title] => 
        [deleted]=>0
    )

[1] => Array
    (
        [image] => http://image1.jpg
        [title] => 
        [deleted]=>1
    )

[2] => Array
    (
        [image] => http://image2.jpg
        [title] => 
        [deleted]=>0
    )

The explanation is not very detailed, but hopefully it's understandable :)

Sign up to request clarification or add additional context in comments.

1 Comment

Problem is that i dont have any forms and I read data from xml. I found a solution. First read data from database with key and image then use in_array($database_images, $xml_images) and write the result to new array, then delete images from this array from database, I hope you understand, For me it's working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.