0

I'm using this code to validate my my html form and I now need to add the form data into a table in mysql. How do I proceed I know the basics of creating a connection and sql databases but since I've already used the form's submit button i don't know how to get the data to a place where I can insert it again

<?php
// define variables and initialize with empty values
$nameErr = $passErr = $emailErr =$cpassErr="";
$name = $pass = $cpass = $email = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["username"])) {
        $nameErr = "Enter Username";
    }
    else {
        $name = $_POST["username"];
    }

    if (empty($_POST["password"])) {
        $passErr = "Enter password";
    }
    else {
        $pass = $_POST["password"];
    }
       if (empty($_POST["cpassword"])) {
        $cpassErr = "Retype password";
    }
    else {
        $cpass= $_POST["cpassword"];
    }

    if (empty($_POST["email"]))  {
        $emailErr = "Enter email";
    }
    else {
        $email = $_POST["email"];
    }


}
?>

<html>
    <head>
    <style>
     .error {
    color: #FF0000;
        } 
    </style>
    </head>
    <body>
   <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <table border="0" cellspacing="20">
      <tbody>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" accept="" value="<?php echo htmlspecialchars($name);?>">
                    <span class="error"><?php echo $nameErr;?></span>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="text" name="password" accept="" value="<?php echo htmlspecialchars($pass);?>">
                    <span class="error"><?php echo $passErr;?></span></td>
            </tr>
            <tr>
                <td>Confirm Password:</td>
                <td><input type="text" name="cpassword" accept=""value="<?php echo htmlspecialchars($cpass);?>">
                    <span class="error"><?php echo $cpassErr;?></span></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="text" name="email" accept="" value="<?php echo htmlspecialchars($email);?>">
                    <span class="error"><?php echo $emailErr;?></span></td></td>
            </tr>
        </tbody>
    </table>
       <input type="submit" name="submit" value="Submit">
   </form>
    </body>

</html>

Code for the connection

<?php
$host="localhost";
  $username="root";
  $password="root";
  $db_name="LSDB";

    $con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  var_dump($_POST);

  $u=$_POST['username'];
  $p=$_POST['password'];
  $e=$_POST['email'];
  $ph=$_POST['phone'];

  $sql="INSERT INTO register (username,password,email,phone)
     VALUES 
     ('$u','$p','$e','$ph')";

  if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
mysqli_close($con);
?>
8
  • 1
    You already assigned your data from form to variables, now extabilish the connection and use those variables Commented Mar 10, 2014 at 20:45
  • where should I place the code for creating the connection and inserting the values? Oh and dont bother about that entry for the phone it isn't meant to be there anyway Commented Mar 10, 2014 at 20:56
  • Sidenote: Your var_dump($_POST); won't show anything, because you have it "before" they've been assigned. Plus, why am I having a "déjà vue" for this code? Commented Mar 10, 2014 at 21:20
  • If you're not connecting at all, try it without the quotes $con=mysqli_connect($host,$username,$password,$db_name); Commented Mar 10, 2014 at 21:25
  • @fred how should I combine the code to get insertion of records done post validation i.e after I've clicked on submit Commented Mar 10, 2014 at 21:28

2 Answers 2

1

first off i would suggest you escaping the inputs.

also worth noting you could use prepared statements and object oriented way of mysqli as most of the documents on OO are clearer than the procedural way.

like :

<?php
$u=striptags($_POST['username']);
$p=striptags($_POST['password']);
$e=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$ph=(int)$_POST['phone'];

$mysqli = new mysqli($host,$username,$password,$db_name); 
$query = "INSERT INTO register (username,password,email,phone) VALUES (?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssi", $u, $p, $e, $ph);
$stmt->execute();
$mysqli->close();

?>

it would not also hurt using hash on your password like :

<?php

$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$passh = crypt($pass, '$6$'.$salt);
?>

do note that you will need to store the salt in mysql also so you can compare it later

so with these your passwords are safer and if your database gets stolen the passwords will remain hashed.

Sign up to request clarification or add additional context in comments.

5 Comments

Just to note the prepared statements prevent sql injection :)
I just tried the code and I got the following errors gyazo.com/7b175b5e292cd69c0c15620f67fe0654
three first errors are your fields were empty so the problem is at the html if you did enter data to the forms, and the fourth error is pointing towards that the connection isn't working. you could use separate file to process the data like action="addtosql.php"
this is the entire code I'm using now pastebin.com/Er1Swh9Q and this is the output gyazo.com/23d9be57ad2e3dc29b0665707636e03c when I correct the strip tags to strip_tags this:gyazo.com/e3d86570d240d7e77ec53daf8c3eb5d2
lol sorry my bad for the strip_tags error bit sleepy :). the undefined index errors are caused by "empty" fields. and the two last errors are pointing to wrong password and thus it cannot instantiate the object.
0

When the user submits the form, if the validation was successful, then you should execute a process function, where you can place as much instructions as you need, including storing the data in a database, or printing it in an auto-generated webpage. Everything you need.

In another order of things, looks like that code of you is too simple and hence vulnerable to cross-site scripting. You should not only validate if the fields are empty or not, but also you should use some regular expressions and the function preg_match( ) to filter which characters are entered. The best protection is to allow the user enter only the characters that are needed in each field, and not any others than those.

Example on how to handle the logic of the form:

if ($_POST['_submit_check']) {
    // If validate_form() returns errors, pass them to show_form()
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        // The data sent is valid, hence process it...
        process_form();
    }
} else {
    // The form has not been sent, hence show it again...
    show_form();
}

3 Comments

can you elaborate on how to create a process function to deal with the data?I'm not too concerned about the security atm I want to get the data inserted into the sqlserver.I want to insert the data into sql if the validation turns out to be true and preferably on the same page
OK, I will add an example code... from my own programs. Just wait.
When the user submits the form, '_submit_check' is equal to 1

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.