Blog on hold: This blog is currently on hold. Please visit thoughts.keranmckenzie.com for new blog posts

Watch Keran's YouTube Channel #theRandomnessProject


PHP tricks

Tweet 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 [...]

phpAs 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.

Support Studiowhiz.com

One Response

[...] of experience locked up in my head. You’ll find strange things on there like my post about me trying to program again, maybe a post or two about building wealth online, or garnering more traffic for your [...]