开发者

loop through mysql database records and change phone formats

I'm working on a legacy database table that ha开发者_开发百科s 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


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.


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?
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜