循环遍历mysql数据库记录并更改电话格式

发布于 2024-08-23 09:50:09 字数 126 浏览 11 评论 0原文

我正在处理一个有电话号码的旧数据库表。字段,

但问题是所有条目(超过 4k)的

格式各不相同。

我想知道是否有一种快速方法可以通过使用 PHP 循环记录并将记录更新为特定的电话格式来修复它们

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在风中等你 2024-08-30 09:50:09

4K 听起来根本不像很多唱片。

我敢打赌,不同的格式可以分为有限数量的组合。

我想知道是否可以通过一些明智的 SQL 查询来实现。如果您的 RDBMS 具有正则表达式和字符串替换功能,您可以使用一些 UPDATE 指令来管理它。如果没有,任何能够查询数据库、进行字符串替换和更新的语言都可以完成这项工作。

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.

茶花眉 2024-08-30 09:50:09

我同意 4k 记录没有什么可担心的。我建议查询电话号码和表的主 ID,从电话号码中删除所有字符,然后将其处理为您想要的格式。或者,您可以将其保留为仅数字,并在每次显示数字时使用前端修改该数字。下面是一些未经测试的脚本,您可以尝试使用。不处理分机并且预计有 10 个号码。

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

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?
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文