Solved

Insert Value into table from php drop down and submit button

Posted on 2006-07-19
13
595 Views
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)
************code*****************


 <?
$user = "rr";
$pass = "1234";
$server = "host.com";
$db = "the_DB";


$id=$_GET["id"];
$submit=$_GET["submit"];

$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
}else
{$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>";

}reset($result);
?>

</select>
***************code*********************

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
0
Comment
Question by:Roba122
  • 5
  • 4
  • 2
13 Comments
 

Author Comment

by:Roba122
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
0
 
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 = "host.com";
$db = "the_DB";
// and so on...
0
 

Author Comment

by:Roba122
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?
0
 
LVL 5

Expert Comment

by:koolie
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 -----
<?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);
     mysql_select_db($DB);
     return $conn;
}

?>

Let me know if this helps...
0
 

Author Comment

by:Roba122
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?
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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.
0
 

Author Comment

by:Roba122
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.


Similarly

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

Thanks
0
 
LVL 5

Accepted Solution

by:
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>
</select>

I was referencing a textbox...to 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.
0
 

Author Comment

by:Roba122
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
0
 
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:

http://www.php.net/manual/en/language.variables.predefined.php#language.variables.superglobals

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>
</select>
<textarea name="tarea">This is a text area</textarea>
<input name="sendit" type="submit" value="SEND NOW">
</form>

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";
      }
        die();

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 form...it 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:

'This%20is%20a%20text%20area'

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:

http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html

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!
0
 
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>
</select>

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

http://www.w3schools.com/jsref/jsref_events.asp
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
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 create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now