2

i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.

Okay here's what i want to do. I have a form which have two types of input and a selection 1. input type text 2. input type radio 3. selection

Here's the HTML code :

<form action="" method="post" enctype="multipart/form-data">

  <strong>Your Name: </strong><br>
     <input type="text" name="myname" value="" />
  <br /><br/>    

  <strong>Which class type you want:</strong><br>
    <select name="selection">
      <option value="A">A</option>
      <option value="B">B</option>
      <option value="C">C</option>
    </select>

  <strong>Do you agree?</strong><br>
    <input type="radio" name="agree" value="Yes"> or 
    <input type="radio" name="agree" value="No">


  <input type="submit" name="submit" value="Submit">

</form>  

I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)

MySQL table : info structure : 1. name 2. class 3. agree

I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree

P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.

Can someone write a php code example on how can i do this?

Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.

4 Answers 4

3

1. There is a problem with your radio element. The name should be the same for both options.

It should be like this:

<input type="radio" name="agree" value="Yes"> or 
<input type="radio" name="agree" value="No">

2. You can access everything in the $_POST array, since you are using the method post for the form.

$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];

3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.

This would be a sample code, to do the escaping and the query.

// write a function somewhere, to use as a shortcut 
// for escaping data which will be used in a query
function sql_escape($str){
    return "'".mysql_real_escape_string($str)."'";
}

// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
                    sql_escape($_POST['myname']),
                    sql_escape($_POST['selection']),
                    sql_escape($_POST['agree']));

// finally run it
$result = mysql_query($query);
Sign up to request clarification or add additional context in comments.

Comments

2

I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong. Considering your form is fairly simple you would not need this. @Shef's code would certainly do the job but I thought you might be interested in some more.

    <?php
    // check the form has been submitted
    if (isset($_POST['submit'])) {
        // escape the form fields and assign them to variables
        // validate myname to ensure the user entered data
        if (isset($_POST['myname']) && $_POST['myname']!='') {
            $myname = mysql_real_escape_string($_POST['myname']);
        } else {
            // create an error variable array to store errors to display
            $errors[] = 'Please enter your name'; 
        }

        // no need to validate selection here as it alway's has a value
        $classtype = mysql_real_escape_string($_POST['selection']);

        // validate agree unless you want to add 'checked' to one of the values
        if (isset($_POST['agree']) && $_POST['agree']!='') {
            $agree = mysql_real_escape_string($_POST['agree']);
        } else {
            $errors[] = 'Please tell us if you agree?'; 
        }

        //if errors found tell the user else write and execute the query
        if ($errors) {
            $message = '<p class="error">We found a problem:</p><ul>';
            foreach($error as $msg){
                $message .= '<li>'.$msg.'</li>';
            }
            $message .= '</ul><p>Please fix the error/s to continue.</p>';
        } else {
            // write the query
            $query = "INSERT INTO table (myname, classtype, agree) VALUES ";                           
            $query .= "('$myname','$classtype','$agree')"
            // run the query
            mysql_query($query);
            $message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
        }
    }

    // print the message
    // show the variables in the form field so they don't need re-input
    if ($message!='') { echo $message; }
    ?>
    <form action="" method="post" enctype="multipart/form-data">

      <strong>Your Name: </strong><br>
        <input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
      <br /><br/>    

      <strong>Which class type you want:</strong><br>
        <select name="selection">
          <option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
          <option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
          <option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
        </select>

      <strong>Do you agree?</strong><br>
        <input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or 
        <input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>

      <input type="submit" name="submit" value="Submit">

    </form> 

Also: @sqwk, Don't point people towards w3schools, see this: http://w3fools.com/

1 Comment

You are certainly opening up new holes, but I won't get into that. I am just giving an advice: don't ever teach an unsafe code practice to someone who has no idea where the code is leading. You just learned SQL injection protection, next stop is XSS. Keep going...
1

Check whether there is any data in the $_POST array and get the values from it.

Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp

(You do have to make the changes that Shef suggested, though.)

Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.

2 Comments

what's data integrity? sorry i'm new
If I edit the values to your radio box in the HTML source and submit the form you could suddenly have 'maybe' saved in your DB. More importantly though check out SQL Injection.
1

check this simple example:

<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>

after you submit form, you can take name and sname.

welcome.php::

    <?php 
$name= $_POST["name"]; 
$sname= $_POST["sname"]; ?>

now you can use this variables as if you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.