Tyler Hughes
Tyler Hughes

Reputation: 612

PHP/MySQL: Storing Multiple Values in Database Column

I have a form that allows you to input phone numbers. You can click a plus button and add more fields. I need to store all those values in the database but only have one column to do it.

With the phone number is also a type dropdown where you can select things like: Mobile, Home, and Work. So I need a way to pair the type and number together for each field, then combined all the pairs together. Then later on when I need the information, to be able to pull it all out and place all values into an array. Almost like encrypting and decrypting.

I was thinking of something like:

type:number;type:number;type:number;type:number;type:number;type:number

Being able to use explode and implode to encrypt and decrypt.

But how good is this? And I also have a search feature which searches for phone numbers. I imagine my way can't be easy for a search function to look through.

Upvotes: 0

Views: 2526

Answers (3)

rockstar
rockstar

Reputation: 3538

PHP Code :

$delimiter = "|";
if (isset($_POST['editfill_mobile'])) {
        $mobileArray = $_POST['editfill_mobile'];
        $replymobile = "";
        $i = 0;
        foreach ($mobileArray as $key => $value) {
            $i++;
            $replymobile .= $value;
            $replymobile .= $delimiter;
        }
    }

Store this $replymobile as is in the database column .

Eventually u may need to split the above string to parse data from it when you query the database ....

Upvotes: 0

jtheman
jtheman

Reputation: 7501

I would say its a bad idea. If you planning to have limited types of numbers ie Home, Work, Mobile etcetera I suggest you to add columns for each number. Otherwise make a separate database table "phone_numbers" and relate this to your customer id or similar and add as many numbers you like. Searching will just be both faster and more easy to implement.

If you still need to store them in a single field then use php implode() and explode() as you suggest. In my cases where I do this I would use a character that my customers would rarely think of such as a pipe symbol "|" as a delimiter. Of course I need to use str_replace or such technique to filter out if my users accidentally has used it in the input but best if its a character seldom used.

Upvotes: 4

jeroen
jeroen

Reputation: 91792

Searching is definitely not going to work. Especially if you use search for something like auto-completion, you want to be able to quickly select all numbers starting with certain digits.

There are two options: Add more columns or add a separate table for phone numbers containing just the type, number and id of the person.

Upvotes: 2

Related Questions