As you know from my earlier post I’m rusty when it comes to coding. We’ll I’m working on a small project in my weekends (which I’ll unveil in the coming weeks) and while it’s more a proof of concept than anything, I’m using it as an excuse to brush up on my PHP skills - not that I program any more in my day job (yeah!)
So I thought I’d share a couple of things I’ve found - that are probably old news to you.
Remove duplicates from an array: a really, really simple thing to do.
Lets say I have an array $myArray = (’Red’, ‘Green’, ‘Red’, ‘Blue’, ‘Red’, ‘Yellow’) and I didn’t want Red in there 3 times. PHP has a nice little function called array_unique().
$myArray = ('Red', 'Green', 'Red', 'Blue', 'Red', 'Yellow');
$clean_array = array_unique($myArray);
$clean_array now looks like (’Red’, ‘Green’, ‘Blue’, ‘Yellow’)
Insert multiple rows with one insert:
I always thought you couldn’t add multiple rows to a table with an insert. I thought each insert had to be a single row. Well this is not so as I found out today. Lets say you are adding 10 items to a ‘tag’ table (id, tag) you can do it like this:
INSERT INTO 'tag' (tag) VALUES
('apple'), ('windows'),
('css'), ('seo'), ('html'),
('design'), ('xhtml'), ('lcd'),
('usb'), ('crt');
Of course you can dynamically build the values and pop in many rows at once. I saw a post on some blog (I’ve misplaced the link since getting this to work) that mentioned adding many megabytes of data this way - I can’t say I’d recommend that as a particularly efficient way - but for adding maybe 50 tags it’s jolly fast.
On a side note, anyone know of anyway to get mysql to return the id’s for the rows it just added. If you are adding one row at a time of course you can use ‘mysql_insert_id()’ to return the id (only if you are using auto_increment) of the previous insert. Sadly this doesn’t seem to work with multirow inserts.