Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How to input radio button and checkbox response into MySQL database?

Posted on 2006-05-23
25
Medium Priority
?
906 Views
Last Modified: 2008-01-09
Hi!

I am trying to create a simple online survey (using PHP and MySQL) which includes radio buttons, checkboxes and textareas.

Before posting this question, I spent quite a while reading the previously posted questions and responses about topics similar to mine.  But for some reason, I could not figure out. I am a real novice in PHP and MySQL.
I will truly appreciate if you experts may kindly help me out.

Thanks a lot!

duta

Tuesday (May 23, 2006) at 11:13 a.m.



__________ form.php  ______________________________________________


<html>
<head><title>PHP Survey-</title></head>
<body>

<form action="process.php" method="POST">
<ul>
<b>Please fill the form accurately.</b></FONT></ul>

<ul><ul>


<P><li><strong>Gender:</strong><br>
<INPUT TYPE="RADIO" NAME="gender" value="male" size="35">                     Male<br>
<INPUT TYPE="RADIO" NAME="gender" value="female" size="35">      Female<br>
<INPUT TYPE="RADIO" NAME="gender" value="neutral" size="35">      Neutral<br>

</li>

<P><li><strong>Favorite Fruits:</strong><br>
<INPUT TYPE="checkbox"      NAME="fruit"            value="Apple"      size="35">      Apple<br>
<INPUT TYPE="checkbox"      NAME="fruit"            value="Orange"       size="35">      Orange<br>
<INPUT TYPE="checkbox"      NAME="fruit"            value="Banana"      size="35">Banana<br>

</li>

<p><li><strong>What is your evaluation of this movie?</strong><p>

<select name="movie">
<option> Awesome!
<option> Good
<option> Poor
</select>

</li>
</ul></ul>
<ul><ul>

<p><li><strong>Write about Your Work Attitude: </strong><br>
<textarea NAME="block" cols="80" rows="10"><?php echo $_POST['block'] ?></textarea>

<br><br>
<INPUT TYPE="SUBMIT" NAME="SUBMIT"       VALUE="SUBMIT" >
<INPUT TYPE="RESET" NAME="RESET"       VALUE="RESET">

</li>
</ul></ul>
</FORM>
<hr>
</body>
</html>

______________ process.php _____________________________________________
<html>
<head>
<title>PHP Survey</title>
</head>
<body>
<?php


$gender = $_POST['gender'];
$fruit=$_POST['fruit'];
$movie = stripslashes($_POST['movie']);
$attitude =$_POST['block'];





if (!isset($gender))
echo("You didn't enter your gender<br>");

if (!isset($fruit))
echo("You didn't enter your race.<br>");

if (!isset($movie))
echo("You didn't enter your evaluation<br>");

if ( !isset($gender) || !isset($fruit) || !isset($movie) || !isset($attitude))
{
echo("<h3>" .$fname.",You responded the questions accurately; Thanks!</h3>");
echo "<h4> Here are your records </h4>";


echo ("<p>Gender: " . $gender);
echo ("<p>Fruits: " . $fruit);
echo ("<p>Movie: " . $movie);
echo ("<p>Attitude: " . $_POST['block']);
}
else

{
echo("<h2>Please, answer all questions</h2>");

}
$to  = 'duta@hotmail.com'';

// subject
$subject = 'Testing survey4 ';

// message
$message1 = "
<html>
<head>
  <title>Your Response </title>
</head>
<body>
  <p>Here are Your Response</p>
  <table width='76%' border='1' cellspacing='1' cellpadding='1'>

   <tr>
     <th> Gender </th><th>Fruits</th><th>Movie</th><th></th><th>Attitude</th></tr>
   
   <tr>
     <td align='center'>$gender</td><td align='center'>$fruits</td><td align='center'>$movie</td>
     <td align='center'>$attitude</td></tr>
  </table>
</body>
</html>
";
// $headers="<h2>Online Survey</h2>";
mail($to, $subject, $message1, $headers);



$conn = mysql_connect("localhost","my_user_name", "my_password");

if (!$conn)
{ die ('Could not connect:' . mysql_error());}
else
{echo "You are connected!<br>";}

 $sql="Create database my_db";
 mysql_query ($sql, $conn);

mysql_select_db ("my_db", $conn);

// Create table
$sql="create table my_table (gender enum('female', 'male', 'neutral'),fruit enum('apple' 'orange', 'banana'), movie enum('awesome', 'good', 'poor'), attitude text)";
mysql_query($sql, $conn);

// Insert date into MySql table
mysql_query ( "INSERT INTO my_table(gender,fruit,movie,attitude)
VALUES ('$gender', '$fruit','$movie','$attitude') " );
 echo "<br> Data inserted!";

// Output client's input

echo "<table width='76%' border='1' cellspacing='1' cellpadding='1'><tr><th>
Gender</th><th>Fruit</th><th>Email</th><th>Movie</th><th>Attitude</th>";


$result =mysql_query("SELECT * FROM my_table");
while ($row=mysql_fetch_array($result))
{
  echo '<tr><td>';
 
  echo $row['gender'];
  echo '</td>';
  echo '<td>';
  echo $row['fruit'];
  echo '</td>';
  echo '<td>';
  echo $row['movie'];
  echo '</td>';
   echo '<td>';
  echo $row['attitude'];
  echo '</td>';
  echo "</tr><br>";
   
}

echo "</table>";


?>

</body>
</html>

_____________________________________________________________________________________


0
Comment
Question by:duta
  • 12
  • 10
  • 3
25 Comments
 
LVL 5

Expert Comment

by:kkhipple
ID: 16743865
Something along the lines of if isset( $_POST['gender'] )  {  echo $_POST['gender'];  }    should be able to display the gender value if it is set.
0
 

Author Comment

by:duta
ID: 16743909
TO: kkhipple:

Thank you for your kind, prompt response.

I think that a client's response to "gender" question should first be put in MySQL database before it is displayed.
The biggest issue here is how to input a client's response to the questions into MySQL database.

Thanks!

duta
Tuesday at 11:27 a.m.
0
 
LVL 5

Expert Comment

by:kkhipple
ID: 16743967
This is a database question then?

I would have a database field named gender where you would store the gender of the response
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 3

Expert Comment

by:jmar_click
ID: 16744013
Hi Duta,

On the gender selection, I mistakenly read the options are, male, female, neutered, and thought, 'what the heck kind of survey is this?'

But anyways,

The form.php looks fine, except for one thing, on the "Write about Your Work Attitude:" question, you echo the block variable, I assume so that a user doesn't have to retype their text. But you should check to see if the form was submited first otherwise the script won't find the variable, do this like this:
<?php
$block = ""
if(!empty($_POST["block")){
$block = $_POST["block"];
}
?>
<textarea NAME="block" cols="80" rows="10"><?php echo $_POST['block'] ?></textarea>

as for the process.php script

You should turn this
$gender = $_POST['gender'];
$fruit=$_POST['fruit'];
$movie = stripslashes($_POST['movie']);
$attitude =$_POST['block'];


if (!isset($gender))
echo("You didn't enter your gender<br>");

into something like this:
$pass_validation = true; //true is a boolean value

if(empty($_POST["gender"])){
$pass_validation = false
echo "You didn't select a gender";
}

you can use if(!isset($_POST["gender"])) if you're more comfortable, i'm just used to empty()

then only run the mail if

if($pass_validation == true){
send e-mail
do database queries
}

I'm wondering why you're creating the table everytime though. This would fail if you already have a table with the same name as the one you're trying to recreate.

This isn't a complete answer but it should help you out a bit.

-Javier
0
 

Author Comment

by:duta
ID: 16744104
TO: jmar_click and kkhipple:

Thank you so much for your kind, prompt response.

Yes, some of the questions may look a little weird, but my real survey question is not like that. I tried to make it as simple as possible so that you may better and quicker help me out.

Would you kindly check my table's variable format?  I am not quite sure whether I may use enum for radio buttons and checkboxes.
_____________  script to create table _________________________________________________________________
$sql="create table my_table (gender enum('female', 'male', 'neutral'),fruit enum('apple' 'orange', 'banana'), movie enum('awesome', 'good', 'poor'), attitude text)";

______________ the end of the script _________________________________________________________________

Thanks a lot!

duta
Tuesday at 11:45 a.m.

0
 

Author Comment

by:duta
ID: 16744135
TO: All:

There are several problems with my script. One of the biggest problems is that MySQL does not respond to the following  script to input client's response into MySQL table:
_______________________________ The beginning of script ____________________________________

// Insert date into MySql table
mysql_query ( "INSERT INTO my_table(gender,fruit,movie,attitude)
VALUES ('$gender', '$fruit','$movie','$attitude') " );
 echo "<br> Data inserted!";
_______________________________ End of script  ______________________________________________

Thanks!

duta
Tuesday at 11:49 a.m.
0
 
LVL 5

Expert Comment

by:kkhipple
ID: 16744193
I would not restrict the mysql table to certain responses.
Keep the table field to allow any input and use ur form to restrict what goes into your table
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16744206
store your query in a variable then echo it before running the query and show us what the echo produces.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16744214
like this
$insert_qry = "INSERT INTO directory_categories VALUES (NULL, '$_POST[txt_dircat]','$_POST[sel_cat]')";
            echo $insert_qry;
            mysql_query($insert_qry);
0
 

Author Comment

by:duta
ID: 16744396
TO: jmar_click:

Thank you so much for trying so hard to help a real notice out.

I modified the script as you kindly suggested, and responded to the questions and clicked "Submit" button. I got the out as below.  The script failed to create a table I intended to create.



_________ Output when "Submit" button was clicked __________________________

Please, answer all questions
You are connected!
INSERT INTO my_table(gender,fruit,movie,attitude) VALUES ( 'female','Apple', 'Awesome!','') Gender Fruit Email Movie Attitude
_________________________________________________________________________

Hope that this feedback may of any help to you in trying to help me!

Thanks a lot!

duta

Tuesday at 12:21 p.m.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16744828
Use this to create your table.

You should create it with a separate script. If you try to create it everytime the process.php script is run you'll get errors, from there you won't be able to insert and your errors will escalade, so its best to make sure the beggining works first.

CREATE TABLE `hriders`.`my_table` (
  `surveryID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `gender` VARCHAR(45) NOT NULL DEFAULT '',
  `fruit` VARCHAR(45) NOT NULL DEFAULT '',
  `attitude` TEXT NOT NULL DEFAULT '',
  PRIMARY KEY(`surveryID`)
)

surveryID is a primary key, unisined, can't be null and it auto increments
gender is a varchar field, as is fruit
attitude is a text field so it can store larger amounts of text

I'll be back with your insert query in a bit
0
 

Author Comment

by:duta
ID: 16744981
TO: jmar_click:

Thanks a lot for kindly trying to help me.

By the way, the radio buttons and check buttons do not work by all means.

I read previous some of previous posts about a similar issue, and I noticed that they used array (something like "check[]") for values of checkboxes. But I could not completely comprehend how it worked. I guess that I might have to use an array to make checkboxe and radio buttons to work properly.

Thanks again!

duta
Tuesday at 1:23 p.m.
0
 

Author Comment

by:duta
ID: 16745012
TO ALL:

The url of the previous post for an issue similar to mine is :

http://search.experts-exchange.com/search.jsp?query=%22php+survey+help+needed%22&searchType=all&Submit.x=0&Submit.y=0¤tTAID=103


The reason why I am asking for your help is that I could not understand it quite clearly.

Thanks!

duta

Tuesday at 1:27 p.m.

0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16745050
You don't need to create an array for the radio buttons because you are only expecting one of the choices. But you do need an array for the check boxes because they all have the same name and you want to get all the choises the user gave you.

This brings up a question. How are you planing to store the fruit choices? one choice per field? or all choices together as a string, maybe a comma delimeted string?

fruit1,fruit2,fruit3

This script also looks kinda odd for a survey? is it for a school project?
0
 

Author Comment

by:duta
ID: 16745283
TO: jmar_click:

Thanks again for your very kind response and tips.

This is neither a school project nor a work project. I am doing this to create a simple workable online survey as a  part of my effort to learn PHP and MySQL. Yes, my work may look very odd. I am going to post my work in my new web site where I will upload my work as a zip file.

I will be back to you as soon as I am done with uploading it.

Thanks again!

duta

Tuesday at 1:55 p.m.
0
 

Author Comment

by:duta
ID: 16745954
TO: All:

Hi!
I put my scripts in my web site (http://www.nice-man.com). You may download my scripts by clicking "Click here .. " link at left-top of the page.

Hope you experts may kindly help me out.

Thanks again!

duta
Tuesday at 3:09 p.m.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16746003
I have the script you need almost writen up with comments to help you understand why and how things work. I'm currently at work and need to get some stuff done. I'll be home in about 5 hrs and i'll help you from there. Do you have an e-mail address I can send the scripts to?
0
 

Author Comment

by:duta
ID: 16746817
TO: jmar_click:

Thank you so much for your kind response and for extraordinary effort to help me.

Yes, my e-mail address is "youngtiger"@mchsi.com" (Hope that posting my email address here may not violate any site rules).

The biggest bottleneck is that there is no communication between PHP script and MYSQL datebase when radio buttons and/or checkboxes are clicked.

Thanks again!

duta
Tuesday at 4:54 p.m.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16746832
Thanks duta,

You're almost there the way you have your script, but you have too much going on and you'll need to break things apart a bit. Especially if you are just learning php and/or mysql. I will show you all of this on the scrips i'll e-mail you.

I also included the code to handle check boxes. Radio buttons aren't a problem and don't need any special attention like checkboxes do.
0
 
LVL 3

Accepted Solution

by:
jmar_click earned 2000 total points
ID: 16748016
OK here is the finished code, I didn't add the mail function, but that looked like it worked on your script. I also used the fields from earlier, so I didn't use the e-mail field. Just stick there in your server, and supply your mysql log in information in the connection file

SQL Create Table Code, database name is assumed to be my_db
CREATE TABLE `my_db`.`my_table` (
  `surveyID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `gender` VARCHAR(45) NOT NULL DEFAULT '',
  `fruit` VARCHAR(45) NOT NULL DEFAULT '',
  `movie` VARCHAR(45) NOT NULL DEFAULT '',
  `attitude` TEXT NOT NULL DEFAULT '',
  PRIMARY KEY(`surveyID`)
)
ENGINE = InnoDB;

----------------FORM CODE---------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form action="process.php" method="POST">
<ul>
<b>Please fill the form accurately.</b></FONT></ul>

<ul><ul>


<p><li><strong>Gender:</strong><br>
<input TYPE="RADIO" NAME="gender" value="male" size="35" />                    Male<br>
<input TYPE="RADIO" NAME="gender" value="female" size="35" />     Female<br>
<input TYPE="RADIO" NAME="gender" value="neutral" size="35" />     Neutral<br>

</li>

<p><li><strong>Favorite Fruits:</strong><br>
<input TYPE="checkbox" NAME="fruit[]" value="Apple" size="35" />     Apple<br>
<input TYPE="checkbox" NAME="fruit[]" value="Orange" size="35" />     Orange<br>
<input TYPE="checkbox" NAME="fruit[]" value="Banana" size="35" />Banana<br>

</li>

<p><li><strong>What is your evaluation of this movie?</strong><p>

<select name="movie">
<option selected="selected"> Awesome!</option>
<option> Good</option>
<option> Poor</option>
</select>

</li>
</ul></ul>
<ul><ul>

<p><li><strong>Write about Your Work Attitude: </strong><br>
<textarea NAME="block" cols="80" rows="10"><?php echo $_POST['block'] ?></textarea>

<br><br>
<input TYPE="SUBMIT" NAME="SUBMIT"      VALUE="SUBMIT"  />
<input TYPE="RESET" NAME="RESET"      VALUE="RESET" />

</li>
</ul></ul>
</form>
</body>
</html>

-----------------------------------Process.php code--------------------------------
<?php
//Include Connection File
require_once("dbconnect.php");
?>

<?php
//We'll use this variable to decide if the form passed validation
$pass = true;
//Get variables from the form POST
#first we're going to initialize them, good practice towards qriting secure php, but not neccessary
$gender = "";
$fruit = "";
$movie = "";
$attitude = "";

if(empty($_POST["gender"])){
$pass = false;
echo "Select a gender";
}
else{
//use trim() just to remove any leading or trailing empty spaces
$gender = trim($_POST["gender"]);
}

if(empty($_POST["fruit"])){
echo "Select a fruit";
$pass = false;
}
else{
//use trim() just to remove any leading or trailing empty spaces
      while (list ($key,$val) = @each ($_POST["fruit"])) {
      $fruit .= "$val,";
      }

}

if(empty($_POST["movie"])){
echo "Select a movie";
$pass = false;
}
else{
//use trim() just to remove any leading or trailing empty spaces
$movie = trim($_POST["movie"]);
}

if(empty($_POST["block"])){
echo "Select a attitude";
$pass = false;
}
else{
//use trim() just to remove any leading or trailing empty spaces
$attitude = trim($_POST["block"]);
}

?>


<?php
//Now, if validation was passed, continue
if($pass = true ){
?>
<h3>" .$fname.",You responded the questions accurately; Thanks!</h3>
<h4> Here are your records </h4>
<?php      
      //Display inputs
      echo "Gender: ".$gender."<br />";
      echo "Fruits: ".$fruit."<br/ >";
      echo "Movie: ".$movie."<br />";
      echo "Attitude: ".$attitude."<br />";

      //Next we want to insert the  values into the table
      $insert_qry = "INSERT INTO my_table VALUES (NULL, '$gender', '$fruit', '$movie', '$attitude')";
      echo $insert_qry;
      $qry_state = mysql_query($insert_qry) OR die("<br><br>This error occured when I tried to insert a record: " .mysql_error());

      //If the query was successful, then the function mysql_query() will return a 1 for true which we capture in $qry_state
      if($qry_state == 1){
      echo "<br><br>Your response has been recorded, thanks.<br><br>";
      }


      //Now we want to select all the records from the database table
      $select_qry = "SELECT * FROM my_table";
      $select_results = mysql_query($select_qry);
      //$results_count = mysql_num_rows($select_results);
?>

      <!--Now we can start our HTML table to display the results-->
      <table border="1">
            <tr>
                  <td>Gender</td>
                  <td>Fruit</td>
                  <td>Movie</td>
                  <td>Attitude</td>
            </tr>
            <?php
            //The function mysql_fetch_array() converts the records set into an array that we can look through with a WHILE loop
            while($row = mysql_fetch_array($select_results, MYSQL_ASSOC)){
            ?>
            <tr>
                  <td><?php echo $row["gender"];?></td>
                  <td><?php echo $row["fruit"];?></td>
                  <td><?php echo $row["movie"];?></td>
                  <td><?php echo $row["attitude"];?></td>
            </tr>
            <?
            }
            ?>
      </table>
<?php
}//End main IF
?>




<?php
//Close connection
mysql_close();
?>

-----This is your connection string---------------
<?php
//Set up variables
$dbhost = 'xxxx';
$dbuser = 'xxx';
$dbpass = 'xxxx';      

//Connect to MYSQL
$dbh = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");

//Select database
$selected = mysql_select_db("my_db",$dbh) or die("Could not select database table");

//Establish a database connection
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
?>

This works in my server, it should work on yours too, and may I recommend you read about the functions at php.org

Good luck!
0
 

Author Comment

by:duta
ID: 16748216
TO: jmar_click:

You are just awesome. Your help is extraordinary.

I just checked your comment. It will take a while to finish trying your script which I believe will work flawlessly.

Once I am done with it, I will come back to you with my feedback.

Thanks a lot!

duta
Tuesday (May 23, 2006) at 10:19 p.m.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16748233
:) makes me feel warm and fuzzy inside
0
 

Author Comment

by:duta
ID: 16748319
TO: jmar_click:

Thank you so much for your very, very kind, extraordinary help.

Your scripts worked just great. You are a genius. Wish I may be able to reward you with 1 million points, not the 500 points offered.

I will try to learn more and harder so that I may someday be able to help others as you did to me.

You are just fabulous!

Thanks again!

duta
May 23, 2006, at 10:55 p.m.
0
 
LVL 3

Expert Comment

by:jmar_click
ID: 16756299
I'm glad you got it to work duta, do you understand how and why things work?

It wasn't a difficult question really. There are experts here who are much more knowledgeable than I am...they're the real experts. I still have a lot of learning to do to get to their level. But I never mind sharing what I know with others, thats what EE is all about it.
0
 

Author Comment

by:duta
ID: 16757513
TO: jmar_click:

You are as humble as you are knowledgeable.
It was so thoughtful of you to put a comment on almost each line of your script. I guess you spent quite much time for me. I really love this service and people like you who are always eager to help people who need help.
PHP and MySQL scripts still look not familr to me even though I spent quite much time trying to learn them. I know it takes pain to obtain anything worthy.

My one more salute to you and to others who are always willing to share their knowledge with less knowledgeable people.

duta

Wednesday (May 24, 2006) at 10:27 p.m.
0

Featured Post

Technology Partners: 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!

Question has a verified solution.

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

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to count occurrences of each item in an array.
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…
Suggested Courses

564 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