PDA

View Full Version : deleting multiple records



I am Abby
05-14-2010, 12:40 PM
I'm having trouble deleting all objects with a category of 2 but only 2. Help please.


if ( $_POST['deletechecker'] == 1 )
{
$cat = 2;
$file = '../xml/movies.xml';
$xml = simplexml_load_file($file);

$i = 0;
foreach($xml as $kid){
if($kid->cat[$i] == $cat){
unset($xml->mov[$i]);
}
$i ++;
}

$xml = $xml->asXML($file);
}


xml


<movies>
<mov>
<id>1324</id>
<cat>2</cat>
<movie>Sleepless In Seattle</movie>
</mov>
</movies>

djr33
05-14-2010, 05:15 PM
I know this doesn't answer your question, but since you've posted so many questions about xml (and are running into difficulties with it), the obvious answer to me is that you should use a database. A database is meant for this. XML is well structured and you can do a lot with it, but a database is extremely well structured to the point that you can search for some value (2) and then delete it, output it, modify it, etc.

As for your code:
$i = 0;
foreach($xml as $kid){
if($kid->cat[$i] == $cat){
unset($xml->mov[$i]);
}
$i ++;
}
That's a really awkward way to do a foreach loop. One of the major advantages of foreach is that it automatically deals with the array keys for you.
If you want to track $i yourself, then use a for loop.
Here's how to rewrite the foreach loop into a much easier format. See if this helps:

foreach($xml as $i=>$kid){
if($kid->cat[$i] == $cat){
unset($xml->mov[$i]);
}
}Note $i=> at the start of the loop.
Foreach takes one of the two following formats:
foreach($array as $part)
foreach($array as $key=>$part)

I am Abby
05-14-2010, 05:41 PM
Thanks djr33

I know I really should use a db. I'm new to both php and xml and was wanting to do my pages with only the two. So far it's mostly working out...I do have to use a bit of javascript.

Sorry if I ask too many questions, but you all have been angels about everything.

djr33
05-14-2010, 05:49 PM
It's not that you're asking too many questions, but you're doing all of this the hard way.

There's an inverse relationship between ease of use and easy of complexity.

MySQL is of course harder, but it really is easier for the more complex stuff. Using flat files is really easy, but almost impossible when you want to do anything beyond the basics. XML falls somewhere in the middle. It's main good use is for storage and transfer (outside of a database). But once you start manipulating the data, you are effectively processing everything each time you load the page rather than once as with a database.
The efficiency of MySQL is amazing and I'm not really sure how it works because I know that I can't program anything even close to that using text files (or xml).



Did the code I showed you above help at all? I don't work with XML much so I'm not sure what else to suggest. Someone else should know soon enough, though.

I am Abby
05-14-2010, 10:11 PM
The code you gave me works perfectly for my needs. Thank you.