PHP-Form validation and insertion using MySql

2019-06-13 17:22发布

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);
?>

2条回答
Emotional °昔
2楼-- · 2019-06-13 17:40

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-13 17:45

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();
}
查看更多
登录 后发表回答