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:

$('#insert').bind('submit', function(){
                        var phone = $('[name=phone]').val();
                        var email = $('[name=email]').val();

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="">Verizon</option>
  <option name="email" value="">AT&T</option>

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:

$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: into the email column of the table you specified.

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