PHP While to delete pictures from mySQL database

hi guys,

in need of some advise, I’m busy with a classifieds website where people list the items for sale, but under admin I have a link to delete ALL ads from a client
which must also delete the images on the server for each ad of that client. the script runs perfectly to delete all ads + the client account, but the script only deletes
the first ad’s pictures, the rest of the ads pictures remains on the server? Mayby just something small that I am missing, please help.

the code the delete the images for the ads :

$result = mysql_query("SELECT * FROM listings WHERE client_id='" . $aid . "'");	// GET CLIENT ADS
	
if($result) {					

		
		
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {		// DELETE ALL PICTURES
		
			$images = mysql_fetch_assoc($result);	
					
					$img1 = $images['photo1']; $img2 = $images['photo2'];
					$img3 = $images['photo3']; $img4 = $images['photo4'];
					$img5 = $images['photo5']; $timg1 = $images['thb1'];
					$timg2 = $images['thb2'];  $timg3 = $images['thb3'];
					$timg4 = $images['thb4'];  $timg5 = $images['thb5'];

					if($img1 !="empty") { @unlink('../'.$img1); }
					if($img2 !="empty") { @unlink('../'.$img2); }
					if($img3 !="empty") { @unlink('../'.$img3); }
					if($img4 !="empty") { @unlink('../'.$img4); }
					if($img5 !="empty") { @unlink('../'.$img5); }
	
					if ($timg1 != 'empty') { @unlink('../'.$timg1);}
					if ($timg2 != 'empty') { @unlink('../'.$timg2);}
					if ($timg3 != 'empty') { @unlink('../'.$timg3);}
					if ($timg4 != 'empty') { @unlink('../'.$timg4);}
					if ($timg5 != 'empty') { @unlink('../'.$timg5);}
	
					
		}
		
}

I think your $images assignment is pulling the first record during each iteration of the “While” loop. I’d just get rid of the line altogether and assign $img1 to $row[“photo1”], $img2 to $row[“photo2”], etc…

There’s more that I would do, but this would be the “quick & dirty” solution. Worth a shot, anyway.

hi,

thank you so much, it worked :slight_smile:

Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn’t tie you down so much to a particular database server software.

Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.