Combine the values of two fields in a form into one variable to be inserted into MySQL database table

Here is the simple code that I use to combine the values of two fields in a form into one variable and insert that variable into a database table.

One example of how I used this trick was when I built an SMS-subscriber widget for a website. I needed people to enter their phone numbers into one field, select their phone carrier from another field, and then combine those two fields with an “@” symbol in between to create an email address that was then inserted into the database. These SMS subscribers could then receive the same notice as email subscribers.

Here is the code you use:

<script>
$('#insert').bind('submit', function(){
                        var phone = $('[name=phone]').val();
                        var email = $('[name=email]').val();
                        $('[name=subscriber]').val(phone+'@'+email);
                      });
</script>

Note: #insert in the code above needs to be changed to the id of your form. 

Insert the jQuery code above directly after the beginning of your form, which would look something like this:

<form action="insert.php" method="POST" id="insert">

Next, create a hidden field which will contain the combined values of the two fields:

<input type="hidden" name="subscriber"/>

And finally, create the two fields whose values you want to combine:

Phone #: <input type="text" size=25 name="phone">
Carrier: <select>
  <option name="email" value="vtext.com">Verizon</option>
  <option name="email" value="txt.att.net">AT&T</option>
</select>

In the php file that you use to process the form, you will only need to post the data from the hidden field (which contains the values of the two fields). For instance, using the example above, I would only insert the ‘subscriber’ data into the database:

$v_subscriber=$_POST['subscriber'];
... 
$query="insert into table_name(email) values('$v_subscriber')";

This would insert the value of the subscriber field (which is “phone@email” according to the jQuery above. For example: 1234567890@att.txt.net) into the email column of the table you specified.

Please let me know if you have questions or run into any issues at all.

Meet the author

Libby Fisher is an experienced freelance web developer, recently relocated from Seattle to Boston, and passionate about developing websites that are both aesthetically appealing and intuitively usable - or as she prefers: "beautifully effective."