Insert Value into table from php drop down and submit button

Posted on 2006-07-19
Last Modified: 2008-01-09
Ok here is what I need.  I need a drop down box that pulls from a table a list of records Each record has an Id attached to it.

I need to insert that Id into another table using a where so that I can use another id to specify which record to insert to.

I need this to occur on a submit button event and it needs to refresh the current page ie it cant take the page somewhere else to process.

Here is what I have so far. It generates the drop down but I'm unsure how to pass the result on the submit

For reference the fields are:

Table pull list from: jos_content
Id field: ID
Drop down populate field: title

table to insert into: tbl_cal
Id field of tbl_cal: id ( I will assign this a variable somewhere yet to be determined)

$user = "rr";
$pass = "1234";
$server = "";
$db = "the_DB";


$connection = mysql_connect($server, $user, $pass);// open a connection to the database
if ($id!=null)
$query = "SELECT * from jos_content where id='$id'";// formulate the SQL query
{$query = "SELECT * from jos_content";
$result = mysql_db_query($db,$query ,$connection);// run the query on the database

<form action="<? echo $PHP_SELF; ?>" method="get">
<select name="hh">

<? while($row =  mysql_fetch_array($result))

$id=$row["id"];//presume there is id in db
$item =$row["title"]; //get the first name from db of first in list
echo "<option value='$id'>$item</option>";



I still need to

create the submit button
create the insert query
a msgbox would be nice to indicate success
refresh the current page

Thats about it. My knowledge of php is just weak enough to make this a challenge.

If you can do this without using my code thats fine I'm not tied to it

Thank you
Question by:Roba122
  • 5
  • 4
  • 2

Author Comment

ID: 17142067
I forgot to mention the name of the field to insert the value to

the table is tbl_cal
key field id
and insert value to is : contentid
LVL 50

Expert Comment

by:Steve Bink
ID: 17142171
You have all the basics.  Now you need to make the submit button:

<input type="submit" name="submitbutton" id="submitbutton" value="Submit Now"

As a sidenote, are you sure you want to use method="GET"?  That makes your form submission visible to the user, and also allows them to make their own GET querystrings which can be used to manipulate your site.

For the refresh/after-submit actions, you should be checking for that activity when the page first loads:

if ($_POST['submitbutton'] == "Submit Now") {
  // the form was submitted...take the action you need to take

// continue with the rest of your page
$user = "rr";
$pass = "1234";
$server = "";
$db = "the_DB";
// and so on...

Author Comment

ID: 17142640
Ok, But I need a bit more. I need the code for inserting the value from the drop down into the db whats that?
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 17143046
<input type="text" name="first_name">

<?php include ("db.php")
$conn = database_connect(HOST, USER, PASS, DB, PORT);

$first_name = $HTTP_POST_VARS['first_name'];
$sql = "INSERT INTO `table_name` (database_field_name) VALUES ( $first_name);
mysql_query($sql, $conn);


----put this data in a file called db.php -----
define("HOST", "localhost");
define("PORT", 3306);
define("USER", "db_username");
define("PASS", "db_password");
define("DB", "db_name");

function database_connect($HOST,$USER,$PASS,$DB,$PORT)
     $conn = mysql_connect($HOST . ":" . $PORT , $USER, $PASS);
     return $conn;


Let me know if this helps...

Author Comment

ID: 17148416
not really, The whole point of me giving my variables with the question was that it would be easier to understand the code.  I'm shaky on whats happening here. I dont just want the answer I want to understand the answer and its sort of not relevant compared to the code I posted. I've already connected to the db why would I do it again?
LVL 50

Expert Comment

by:Steve Bink
ID: 17148561
There are two important things in koolie's post:

1) inserting the value into the database

<?php include ("db.php")
$conn = database_connect(HOST, USER, PASS, DB, PORT);

$first_name = $HTTP_POST_VARS['first_name'];
$sql = "INSERT INTO `table_name` (database_field_name) VALUES ( $first_name);
mysql_query($sql, $conn);


2) showing how an include file will help streamline your code.  The code shown below the "----put this data..." should go into a separate file.  If you notice the very first line of the code above is an include() statement.  This tells PHP to go find this file, and insert it verbatim into the current code and resume execution from there.  By putting all your db connection code in the include, you can now ensure you are connecting to the database by using one simple instruction.

Also, remember that when a user selects from the drop-down, they still need to submit the form.  That means browsing to a new page, or at the very least refreshing the one they are at.  In turn, this means the database connection you used to load the page is no longer valid...the scope of PHP resources ends where the execution does.  You WILL need to connect to the db at the beginning of every page.

Author Comment

ID: 17148678
Right, I Know how the include works and I am even using one, For the code I posted it just helps spell things out so its easier for  you guys to answer using my variables and not an include statement, no big deal.  I thought I was very  clear when I originally asking this question.  

Tell me wher Im wrong:

I read routinets post

and I get the following

"Here  is the submit button, et al"

so what I needed to know about the code to get the selected value from the option box and insert it iinto the database on the submit button wasnt present.


I get the following from koolies post

here is a text box and here is how you post the content of the text box to the database great.

  Is it the same as the option box? I have no idea thats why I am asking you guys.

If I am coming off edgy I dont mean to be. I just would like this all distilled into the answer for my question

I am confused on getting my selection from the option box into the database and refreshing the page Im on

thats what Im looking for


Accepted Solution

koolie earned 250 total points
ID: 17148875
No not edgy :-)  I know when I started php all I wanted was the answer and to get things working :-)

I think this should answer your question (I hope)

An option box is written like this:

<select name="selectbox_name">
 <option value="hello">Hello</option>
 <option value="goodbye">Goodbye</option>

I was referencing a reference an option/select box, you would basically do this the same way.  Options do not have names, select tags do.  So, the code to reference the select box would be:
$hi_or_bye = $HTTP_POST_VARS['selectbox_name'];
$sql = "INSERT INTO `table_name` (database_field_name) VALUES ( $hi_or_bye);
mysql_query($sql, $conn);

This then will take the value of the option in the select box.  Does this combined with the other the information help?  I'll be checking periodically throughout the day so yell if this doesnt help you.

Author Comment

ID: 17148984
Yes much clearer one last thing though does this action occur on submit from a submit button or once a value is selected in the option box

i would prefer a submit button to kick this action off
LVL 50

Assisted Solution

by:Steve Bink
Steve Bink earned 250 total points
ID: 17149124
I know the feeling.  You want a straight answer (and honestly, we're giving them!), but you also need the background answer that helps the real answer make sense.  :)  I'll try taking it down another level...

It is important to remember that every form field will be identified by name in the page handling the submission.  In koolie's latest post, he used the $HTTP_POST_VARS array.  That array is deprecated, so I would recommend using $_POST instead.  It IS the exact same concept...just substitute one name for the other.  See here for a brief explanation:

Now, imagine you have this form:

<form name="myform" action="mypage.php" method="get">
<input name="text1" type="textbox" value="blahblah">
<input name="idnumber" type="hidden" value="id3">
<input name="pass" type="password" value="blahblahblah">
<!-- I forget which to use for radio...checked or selected.  one will work, the other does nothing -->
<input name="sex" type="radio" value="Male" selected="selected" checked="checked">
<input name="sex" type="radio" value="Female">
<input name="check" type="checkbox" checked="checked">
<select name="sex2">
<option value="Male">Male</option>
<option value="Female" selected="selected">Female</option>
<textarea name="tarea">This is a text area</textarea>
<input name="sendit" type="submit" value="SEND NOW">

That form appears in myform.php.  Assume the user browses to it, decides to accept the default selections, and submits the form.  Now execution moves to mypage.php.  Create that file and drop this code in:

      echo "SHOWPOST:<br><br>\n";
      foreach ($_POST as $key=>$value) {
            echo "<b>$key</b>:$value:<br>\n";

Now you should be able to see EXACTLY how the form translates over to PHP.  The $_POST variable is set up automatically by PHP, and is an array of all the values sent from the submitted form.  $HTTP_POST_VARS is also created automatically by PHP, but only when a setting called register_globals in on.  Since PHP defaults this setting to off, they decided to deprecate (make obsolete) variables which depend on it.  In fact, since PHP 5.something, the register_globals setting itself is deprecated.  Over all, best to avoid any issues depending on it.

As you can see from the output of that code, each form field is a key in array $_POST.  This means all of the following statements should be true:

$_POST['text1'] == 'blahblah'
$_POST['idnumber'] == 'id3'
$_POST['pass'] == 'blahblahblah'
$_POST['sex'] == 'Male'
$_POST['check'] == 'on'
$_POST['sex2'] == 'Female'
$_POST['tarea'] == 'This is a text area'
$_POST['sendit'] == 'SEND NOW'

This data will only be available in the page which receives the form submission.  If there was no form submission, $_POST should be a blank array.  Also, notice the 'sex' and 'sex2' fields.  More than one option was available...only the selected/checked option value will be available in the post data.  Notice the checkbox field?  They are a little different in that they send a value of 'on' when checked, and are not set if not checked.  Merely checking for their existence provides your value:

$ischecked = isset($_POST['check']);

Another field is 'sendit'.  That was name of the button the user pushed to send the data.  If that button was not pushed, the value is not set.  This can be important if you have more than one submit button on your lets you know which course of action they selected.  Finally, the 'tarea' result may not look exactly like I've written it above.  It MAY look something like this:


That is only HTML entity replacement.  %20 means hex code 20, which is ASCII code 32, which is the space character.  POST, GET, and URL values can have their entities replaced at any time.  It is a good idea to account for that in your code.  Some of the more popular entities can be found at:

Now you've created the form, submitted it, and accessed the results.  Now you need to send it to the database.  Using the most basic construct:

// create the query.  The end result will look like this:
// INSERT INTO MyTable (text, idnumber, pass, sex, check, sex2, tarea) VALUES ('blahblah','id3','blahblahblah','Male','on','Female','This is a text area')

$query = "INSERT INTO MyTable (text, idnumber, pass, sex, check, sex2, tarea) VALUES " .
              "('" . $_POST['text'] . "','" .
              $_POST['idnumber'] . "','" .
              $_POST['pass'] . "','" .
              $_POST['sex'] . "','" .
              $_POST['check'] . "','" .
              $_POST['sex2'] . "','" .
              $_POST['tarea'] . "')";

// execute the query.  $connection should be set up prior to this, preferably in an include file.
mysql_query($query, $connection);

I hope this helps clear up some of the confusion.  I'll be monitoring the thread as well.  Good luck!
LVL 50

Expert Comment

by:Steve Bink
ID: 17149150
To answer your last question, forms are GENERALLY submitted when the user clicks on a submit button.  There are some shortcuts possible, such as pressing the enter key, but these are not necessarily implemented the same way in all forms or across all browsers.

To make the form submit when the user changes a selection, you would need to inject some javascript into the form field's definition:

<select name="mydropdown" onchange="this.form.submit();">
  <option value="1">Option 1</option>  <option value="2">Option 2</option>

You'll find a list of events you can manipulate here:

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question