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