views:

220

answers:

2

Hi,

I'm working on a legacy database table that has a phone no. field

but the problem is that all the entries (over 4k) are in varying

formats.

I was wondering if there was a quick way to fix them by looping through the records using PHP and updating the records to a particular phone format

+1  A: 

4K doesn't sound like many records at all.

And I'd bet that the varying formats fall into a finite number of combinations.

I wonder if it'd be possible with a few judicious SQL queries. If your RDBMS has regular expressions and string replacement functions you could manage it with a few UPDATE instructions. If not, any language with the capability of querying a database, doing string replacement, and updating would do the job.

duffymo
I agree, an UPDATE statement could well do this. You do still have other functions such as SUBSTRING, LEFT, RIGHT, TRIM etc. You can even get the position of a character instance too. Probably best to replicate the table and test it. Again though, as you say, 4K is really quite small.
Kezzer
Thanks but u mean 4000 records is small?
Digital Craft Studios
Yes, very small.
duffymo
+1  A: 

I agree 4k records isn't anything to worry about. I suggest querying the phone numbers and the primary id of the table, stripping all characters from phone number and then manipulating it to be the format you want. Or, you could keep it as only numbers and use your front-end to modify the number every time you display it. Below is a little untested script you can try to use. Doesn't handle extensions and expects there are 10 numbers.

// mysql_connect stuff
$q = mysql_query("Select phone_id, phone_number From phones");
while($r = mysql_fetch_assoc($q)) {
    $num = ereg_replace("[^0-9]", "", $r['phone_number']);
    if(strlen($num) == 10) {
        $num = substr($num, 0, 3) . '-' . substr($num, 3, 3) . '-' . $substr($num,-4);
    }
    $update = mysql_query("Update phones Set phone_number = '" . $num . "' Where phone_id = " . $r['phone_id']);
    // updated?
}
Aaron W.
Thanks Aaron, I think I'll will be walking through this database several times
Digital Craft Studios