Question

I have a MySQL database with a zipcode column. Some of the zip codes are five digits, some are nine digits. I need to insert a hyphen between the fifth and sixth characters if the field is nine characters.

55555 remains 55555

999999999 becomes 99999-9999

I could possibly add them when echoing with PHP, but it would be more efficient if I could just add the hyphen to the data in the zipcode column in the database.

I am at a loss for how to approach this. Any suggestions for a MySQL query help would be greatly appreciated.

Was it helpful?

Solution

If you need to update the value, you could use this update query:

UPDATE yourtable
SET
  zip = CONCAT_WS('-', SUBSTR(zip, 1, 5), SUBSTR(zip, 6))
WHERE
  LENGTH(zip)=9

Please see fiddle here.

OTHER TIPS

<?php
$result = mysqli_query($link, "SELECT zipcode, id FROM table");
while($row = mysqli_fetch_assoc($result) {
    if(strlen($row['zipcode']) > 5) {
        $first_part = substr($row['zipcode'],0,5);
        $second_part = substr($row['zipcode'],5,9);
        $zipcode = $first_part.'-'.$second_part;
        $result2 = mysqli_query($link,"UPDATE table SET `zipcode` = $zipcode WHERE id = {$row['id']}");
    }
}

This is a simple solution to it, adjust the table name in the queries and that should be it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top