Mahadeva
Mahadeva

Reputation: 37

append more than one value in single row using php

I have a table called user having 3 columns namely id, name and phone no.

i want insert data like below clip.

+----+---------------+---------------------+-     
| id | name          | phone no            |      
+----+---------------+---------------------+-     
| 1  |  mahadev      |   +91 XXXXX         |      
| 2  |  swamy        |   +91 YYYYY         |      
|    |               |   +91 ZZZZZ         |      
| 3  |  charlie      |   +91 AAAAA         |      
|    |               |                     |      
+----+---------------+---------------------+-     

Here question is how can i add more than one values (one by one) to same row as showing id = 2 in above clip.

Could anyone please help me on this?

Thanks in advance.

Upvotes: 0

Views: 424

Answers (3)

ilpaijin
ilpaijin

Reputation: 3695

One possible solution could be creating an array of that data and then storing it with serialize() function.

Small example:

$phones_array = array('phone_a' => '+91 YYYYY', 'phone_b' => '+91 ZZZZZ');

serialize($phones_array);

Now your data are serialized into a string, trying var_dump($phones_array) you should get:

string 'a:2:{s:7:"phone_a";s:9:"+91 YYYYY";s:7:"phone_b";s:9:"+91 ZZZZZ";}' (length=66)

You can now insert this value into your table

You can retrieve this data with:

unserialize($phones_array);

Upvotes: 0

dkasipovic
dkasipovic

Reputation: 6120

You cannot do what you intended, how you intended. And for a reason.

One possible solution (bad), would be to make id non-unique and then insert two times id 2, name swamy, phone for two different phones.

Proper solution is to have two tables. One is your current user, which would have only id and name.

Second table is phone_numbers which would have user_id and phone_no. Primary key on that table would be composite of user_id and phone_no so it would prevent duplicates. Then in that table you can insert as many numbers as you need.

In your example you would have two rows with user_id=2, one for each phone number.

Then it is only a matter JOIN to join the two tables together and display your results.

Upvotes: 1

Viktor
Viktor

Reputation: 161

SQL architecture don't allow such things. You need to use more than one row or you can use more than one table with foreign keys. Or you can serialize(phone no) before you put it into mysql.

Upvotes: 0

Related Questions