I am writting a script that checks a folder K:/Comics and inserts each name + number into a database, table name = comics. Now what i would like to do would be to check to see if this comic already exists before we run the insert queries.
Table Structure:
CREATE TABLE IF NOT EXISTS `comics` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`issue` varchar(4) DEFAULT NULL,
`bio` longtext NOT NULL,
`pages` int(10) NOT NULL,
`size` varchar(100) NOT NULL,
`price` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
Code:
<?php
$main_folder = 'K:/Comics/'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
What I thought would work but doesn’t (still adds comics to the db that are already there):
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
What did I forget?!? The documentation said just to add IGNORE in there and it would work…
1 Answer