Purge from tables

A function to purge all rows where $key=$id in multiple tables

<?
function purge_from_tables($id, $tbl_idx) {
	foreach ($tbl_idx as $tbl => $key) {
		if (!is_array($key)) {
			$sql = "DELETE FROM %s WHERE %s=%s";
			
			mysql_query(sprintf($sql, $tbl, $key, $id));
		} else {
			$sql = sprintf("DELETE FROM %s", $tbl);
			$cnt = count($key);
			$keys = array_keys($key);
			
			for ($ii = 0; $ii < $cnt; $ii++) {
				if ($ii == 0) {
					$sql .= " WHERE ";
				} else {
					$sql .= " AND ";
				}
				
				$sql .= sprintf("%s=%s", $keys[$ii], $key[$keys[$ii]]);
			}
			
			mysql_query($sql);
		}
	}
	
	return true;
}

?>

Usage

This function accepts an identifier ($id) as the first parameter and an array ($tbl_idx) as the second, $tbl_idx can be in two forms: array("mytable" => "myidcol") or array("mytable" => array("myidcol" => $id, "mysecondcol" => $id2); the first being used in instances where you want to delete all rows from mytable that have myidcol=$id, and the second being where you want to delete all rows from mytable where myidcol=$id and mysecondcol=$id2. NOTE: this code currently just uses the last open mysql connection, it can be easily modified to use a differant one.


Comments

Add your comment