Archive

Archive for the ‘php Snippets’ Category

MySQL Conditional Insert

December 20th, 2007 ^Lestat No comments

I came across a situation where I needed to pull records from 1 db to another on a recurring basis. I read many different ways to do it via searching around the net. Some of the suggestions included creating a temporary table and copying it over. What was lacking was that sometimes the new table also needed to be UPDATED, as the information changed from the original table.

I’ve come up with a dirty little example to show this can be done. There are more keywords that can enhance the ON DUPLICATE KEY UPDATE function even more. The Example is assuming an “employees” table that looks like so:

employees
id (PK)
first_name

For brevity, I’ve left out connection data etc;

$myArray = array(0 => array('id' => '1', 'fname' => 'Steve'),
                      array('id' => '2', 'fname' => 'sara'),
                      array('id' => '3', 'fname' => 'Matt')
                 );

// Don't forget to validate & clean your data
// Connect to db here 

foreach($myArray as $key => $value){
          $query = "INSERT INTO employees
          (id, first_name) VALUES ('$value[id]', '$value[fname]')
          ON DUPLICATE KEY UPDATE first_name = '$value[fname]'";

          $result = mysql_query($query);

          if(!$result){

                    print("Problem: " . mysql_error() . "");
          } else {

                    print("Success !");
          }

}

Read the manual on this for more information. This snippet will INSERT if a UNIQUE (in this case ‘id’) does not exist. It will UPDATE any existing unique. In this case any existing ‘id’s, the ‘first_name’ column will get updated.

One could also use the REPLACE function. As I understand the difference, REPLACE will DELETE any matching uniques, and INSERT a new record in it’s place.

Comments? Better ways? I’m always up for learning something new so please chime in ;-)

Categories: MySQL, Programming, php, php Snippets Tags:

REGEX Library

March 9th, 2006 ^Lestat 2 comments

I was working up a form and needed to come up with an email regex. I know by now I probably should have my own regex library, or even be able to write my own – but I haven’t exercised my regex skills enough. Often time doesn’t allow an extensive learning period when your already half way through creating a form!

I came across this great regex library at regexlib.com. It’s searchable, offers on the fly tests of user contibuted regular expresssions, rss feeds of recently added patterns, and contains a Cheat Sheet for regex reference.

Of course, programmer beware. Be careful copying and pasting code. And definately test that code before you implement it.

regex, php

Categories: Programming, php, php Snippets Tags: