Hey everyone as you can see I have placed the whole code because
I am trying to connect and write information into a database it is very basic and simple but I don't understand what I am doing wrong????
I am trying to let the user place information into the database by filling up a form and after the user gives his information I want to place it in the database. The database itself is build and tables and rows are made.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $phoneErr = $cityErr = $countyErr = $adressErr = "";
$name = $email = $gender = $phone = $instagram = $facebook = $city = $country = $adress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone = "Phone number is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Amsterdam event attending</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>, <">
Name:
<input type="text" name="name1" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Adress:
<input type="text" name="adress" value="<?php echo $adress;?>">
<span class="error">*</span>
<br><br>
City:
<input type="text" name="city" value="<?php echo $city;?>">
<span class="error">*</span>
<br><br>
E-mail:
<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Instagram:
<input type="text" name="insta" value="">
<br><br>
Facebook:
<input type="text" name="face" value="">
<br><br>
Phone number:
<input type="text" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
}
$servername = 'localhost';
$username = 'root';
$password = '1234';
$database = 'amsterdam';
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender);
VALUES ($_POST[name1], $_POST[adress], $_POST[city], $_POST[email], $_POST[insta], $_POST[face], $_POST[phone], $_POST[gender])";
mysql_close($conn);
?>
</body>
</html>
You should place your VALUES in single quotes. But it's not possible when you write directly your $_POST variables in your query because the single quotes around the $_POST index names will create errors in your code. The main mistake you're doing is to pass your $_POST variables directly into your query which will create serious security issues like SQL injection.
You should do it with mysqli_real_escape_string() function and create variables for each index of the $_POST array.
This is how i would do it:
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$name=mysqli_real_escape_string($_POST['name1']);
$adress=mysqli_real_escape_string($_POST['adress']);
$city=mysqli_real_escape_string($_POST['city']);
$email=mysqli_real_escape_string($_POST['email']);
$insta=mysqli_real_escape_string($_POST['insta']);
$face=mysqli_real_escape_string($_POST['face']);
$phone=mysqli_real_escape_string($_POST['phone']);
$gender=mysqli_real_escape_string($_POST['gender']);
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender);
VALUES ('$name', '$adress', '$city', '$email', '$insta', '$face', '$phone', '$gender')";
$result=mysqli_query($conn,$sql);
I didn't review the code before and the code after. I just corrected the query and the values parameter. I also added the mysqli_query() function to your code. This function is the main function which is responsible for executing the query which you just missed in your code. Let me know if this solves your problem.
I think the problem is that you are trying to open an I/O stream (stream with the SQL server) AFTER writing something on the page.
You can't open stdout (stream to the page you're generating) and then try to open another stream in php. All other streams need to be generated before you write the first character to the page. Try this:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $phoneErr = $cityErr = $countyErr = $adressErr = "";
$name = $email = $gender = $phone = $instagram = $facebook = $city = $country = $adress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone = "Phone number is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Amsterdam event attending</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>, <">
Name:
<input type="text" name="name1" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Adress:
<input type="text" name="adress" value="<?php echo $adress;?>">
<span class="error">*</span>
<br><br>
City:
<input type="text" name="city" value="<?php echo $city;?>">
<span class="error">*</span>
<br><br>
E-mail:
<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Instagram:
<input type="text" name="insta" value="">
<br><br>
Facebook:
<input type="text" name="face" value="">
<br><br>
Phone number:
<input type="text" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
}
$servername = 'localhost';
$username = 'root';
$password = '1234';
$database = 'amsterdam';
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender);
VALUES ($_POST[name1], $_POST[adress], $_POST[city], $_POST[email], $_POST[insta], $_POST[face], $_POST[phone], $_POST[gender])";
mysql_close($conn);
?>
</body>
</html>
A few things I noticed:
You have an if statement that you aren't using
if(isset($_POST['submit'])){
}
$sql definition has a semicolon halfway through it, should probably be:
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender)
VALUES ($_POST[name1], $_POST[adress], $_POST[city], $_POST[email], $_POST[insta], $_POST[face], $_POST[phone], $_POST[gender])";
After you defined $sql, you never actually queried the database with
mysqli_query($conn, $sql);
Finally, you have mixed mysql and mysqli. Your close statement should be
mysqli_close($conn);
There are some other concerns as well but it looks as though some of the other answers have already addressed these.
You need to put your code in your if(isset($_POST['submit'])) curly braces and surround your SQL into else braces. Also, seems like you are using mysql_close() instead of mysqli_close().
if(isset($_POST['submit'])){
$servername = 'localhost';
$username = 'root';
$password = '1234';
$database = 'amsterdam';
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}else{
$name=$_POST['name1'];
$adress=$_POST['adress'];
$city=$_POST['city'];
$email=$_POST['email'];
$insta=$_POST['insta'];
$face=$_POST['face'];
$phone=$_POST['phone'];
$gender=$_POST['gender'];
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender)
VALUES ('$name', '$adress','$city', '$insta, '$face', '$phone', '$gender')";
mysqli_close($conn);
}
}
USE PREPARED STATEMENTS.
Your code can be easily injected. I would recommend using prepared statements.
In this case your prepared statement would look like:
$sql = "INSERT INTO inschrijvingen (name, adress, city, email, insta, face, phone, gender)
VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $adress, $city, $email, $insta, $face, $phone, $gender);
$stmt->close();
$conn->close();
Related
Am just getting my hand on php and I need some little help please. I am working on a registration form with server-side validation, then after validation, the form input should be submitted to the database. I entered data, click submit button, but the data were not submitted to the database. There is no error message. I like you to help me point out where have been wrong and give me a possible solution. Thanks.
Index.php
<?php
include ('signup.php');
?>
<div class="maindiv">
<div class="login"></div>
<div class="wrapper">
<div class="pageintro">
<p>PHP</p>
<p>PROJECT 1</p>
</div>
<div class="regform">
<form name="reg" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<p class="regformp">Fill all Fields</p>
<div class="regwrap">
<div class="inp">Full Name</div>
<div class="inp1"><input type="text" name="FullName" value="<?php echo $FullName; ?>"></div>
<span class="error"><?php echo $fullnameErr;?></span>
<div class="inp">E-Mail</div>
<div class="inp1"><input type="text" name="Email" value="<?php echo $Email; ?>"></div>
<span class="error"><?php echo $emailErr;?></span>
<div class="inp">Password</div>
<div class="inp1"><input type="password" name="Password"></div>
<span class="error"><?php echo $passwordErr;?></span>
<div class="inp">Confirm Password</div>
<div class="inp1"><input type="password" name="ConfirmPassword"></div>
<span class="error"><?php echo $conpasswordErr;?></span>
<div class="inp">Gender</div>
<div class="inp1"><input type="radio" name="Gender" value="Male" <?php if(isset($Gender)&& $Gender=="Male") echo "checked"; ?> >Male <input type="radio" name="Gender" <?php if(isset($Gender)&& $Gender=="Female") echo "checked"; ?> Value="Female">Female</div>
<span class="error"><?php echo $genderErr;?></span>
<div class="inp">Date Of Birth</div>
<div class="inp1"><select name="DayOfBirth"><option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option></select> <select name="MonthOfBirth"><option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option></select> <select name="YearOfBirth"><option>1970</option>
<option>1971</option>
<option>1972</option>
<option>1973</option>
<option>1974</option></select></div>
<span class="error"><?php echo $dobErr;?></span>
<span class="error"><?php echo $mobErr;?></span>
<span class="error"><?php echo $yobErr;?></span>
<div class="inp2"><input type="submit" name="submit" value="SIGN UP"></div></div>
</form>
signup.php
<?php
include ('project1db.php');
//Define variables
$fullnameErr="";
$emailErr="";
$passwordErr="";
$conpasswordErr="";
$genderErr="";
$dobErr="";
$mobErr="";
$yobErr="";
$FullName="";
$Email="";
$Password="";
$ConfirmPassword="";
$Gender="";
$DayOfBirth="";
$MonthOfBirth="";
$YearOfBirth="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["FullName"])){
$fullnameErr = "Name is required";
}
else{
$FullName = test_input($_POST["FullName"]);
//Check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z]*$/",$FullName)){
$fullnameErr = "Enter Valid name please!";
}
}
if(empty($_POST["Email"])){
$emailErr = "Email is required";
}else{
$EMail = test_input($_POST["Email"]);
//Check if e-mail address is correct
if(!filter_var($EMail, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email address";
}
}
if(empty($_POST["Password"])){
$passwordErr = "Password is required";
}else{
$Password = test_input($_POST["Password"]);
//Check password
if(!preg_match("/^[a-z0-9]{6,}$/",$Password)){
$passwordErr = "Password should contain 6+ characters, lowercase and numbers!";
}
}
if(empty($_POST["ConfirmPassword"])){
$conpasswordErr = "Confirm your Password!";
}
else{
$ConfirmPassword = test_input($_POST["ConfirmPassword"]);
//Confirm if password match
if($ConfirmPassword != $Password){
$conpasswordErr = "Password not match!";
}
}
if(empty($_POST["Gender"])){
$genderErr = "Select your Gender!";
}else{
$Gender = test_input($_POST["Gender"]);
}
if(empty($_POST["DayOfBirth"])){
$dobErr = "Select your Day Of Birth";
}else{
$DayOfBirth = test_input($_POST["DayOfBirth"]);
}
if(empty($_POST["MonthOfBirth"])){
$mobErr = "Select your Month Of Birth";
}else{
$MonthOfBirth = test_input($_POST["MonthOfBirth"]);
}
if(empty($_POST["YearOfBirth"])){
$yobErr = "Select your Year Of Birth";
}else{
$YearOfBirth = test_input($_POST["YearOfBirth"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = ""){
$sql = "INSERT into usersignup (FullName, Email, Password, Gender, DayOfBirth, MonthOfBirth, YearOfBirth) VALUES(?,?,?,?,?,?,?)";
if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssisi", $FullName, $Email, $Password, $Gender, $DayOfBirth, $MonthOfBirth, $YearOfBirth);
/* Set the parameters values and execute
the statement again to insert another row */
$FullName = $_REQUEST['FullName'];
$Email = $_REQUEST['Email'];
$Password = $_REQUEST['Password'];
$Gender = $_REQUEST['Gender'];
$DayOfBirth = $_REQUEST['DayOfBirth'];
$MonthOfBirth = $_REQUEST['MonthOfBirth'];
$YearOfBirth = $_REQUEST['YearOfBirth'];
$stmt->execute();
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
else{
}
?>
Database Connection
project1db.php
<?php
$dbhost = 'localhost:3308';
$dbuser = 'root';
$dbpass = '';
$dbname = 'phpproject';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: '.mysqli_error());
}
echo 'Connected successfully';
I have figured out the problem and the problem have been solved.
First problem is with the Mysql database. The AutoIncrement colunm precisely was not set to AutoIncrement. So, I open PhpMyadmin to alter and set the Id colunm to AutoIncrement.
Second Problem was with the conditional statement here:
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = "")
The correct line of code which later worked properly is:
if(empty($fullnameErr) && empty($emailErr) && empty($passwordErr) && empty($conpasswordErr) && empty($genderErr) && empty($dobErr) && empty($mobErr) && empty($yobErr))
This is an important information for those who got confused after they have validated the data input but didn't know how to save the data into the database table.
Please i need help with this form i have those problems Please help me
1- When it submit write error but i see in PHPMyAdmin it's added and record in MySql Database
Example:
Error: INSERT INTO clients (name, email, website, comment, gender) VALUES ('', '', '', '', '')
2- When i don't fill and a required field i see the error message but it's added and record in MySql Database
Example
Email is required
my code is below
<?php
// Database information
$servername = "localhost";
$username = "mymbnwye_mexx";
$password = "";
$dbname = "";
// Database connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// Check input
function checker_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = checker_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = checker_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = checker_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = checker_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = checker_input($_POST["gender"]);
}
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This should work for the PDO Database:
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
I added an If statement to the connection.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
using code that you have mentioned, your sql query will always execute event if there is empty fields because you are writing your query outside of condition.
This code will help solving your problem
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$name = checker_input($_POST["name"]);
$gender = checker_input($_POST["gender"]);
$comment = empty($_POST["comment"]) ? "" :checker_input($_POST["comment"]);
$website = empty($_POST["website"]) ? "" :checker_input($_POST["website"]);
$email = checker_input($_POST["email"]);
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Your code doesn't stop the query being executed if there are missing values. Try something like this instead:
function ValuesCompleted()
{
$values = Array('name', 'email', 'gender');
foreach($values as $index)
{
if(empty($_POST[$index]))
{
return "{$index} not supplied";
}
}
return true;
}
if(isset($_POST) && ValuesCompleted() === true)
{
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$statement = $conn->prepare("INSERT INTO clients (name, email, website, comment, gender)
VALUES (?, ?, ?, ?, ?)");
$statement->execute(Array($_POST['name'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST['gender']);
$conn = null;
}
catch(PDOException $e)
{
// ideally you would print this to a log, not echo it.
echo($e->getMessage());
}
}
else
{
echo ValuesCompleted();
}
I know little about coding.
This is relating to a registration form i am creating. I have created the form. It is adding the form to database. But it want it to be displaying the result, for example - 'Passwords not matching, please try again' on top of the form. How to get that?
Thanks in advance
Here my code:
<?php
$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($conn, 'registration');
if(isset($_POST['submitbutton'])){
if ($_POST['password'] == $_POST['confirm_password']) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$firm = mysqli_real_escape_string($conn, $_POST['firm']);
$check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
$count = mysqli_num_rows($check_email_exists);
if ($count == 0) {
$sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// close connection
mysqli_close($conn);
} else {
die('Email exists, Please use a different email');
}
}
else {
die('Passwords not matching, please try again');
}
}
and here my html
<div class="registration-container">
<div class="registrationpage-heading">
<h2>Kostenlos und ohne Installation testen</h2>
<p>Nutzen Sie den kostenlosen Funktionumfang von bmgenerator zeitlich uneingeschränkt. Weder Bankdaten noch Kreditkarte notwendig.</p>
</div>
<div class="user-login">
<form class="login-form" action="user_login.php" method="post">
<input required type="email" name="email" id="user_email" style="color:#888" size="35" value="E-mail"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="password" name="password" id="user_password" style="color:#888" size="35" placeholder="Passwort"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="password" name="confirm_password" id="user_confirm_password" style="color:#888" size="35" placeholder="Passwort wiederholen"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<select name="gender">
<option>Herr</option>
<option>Frau </option>
</select><br><br>
<input required type="text" name="fname" id="user_firstname" style="color:#888" size="35" placeholder="Vorname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="text" name="lname" id="user_lastname" style="color:#888" size="35" placeholder="Nachname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input required type="text" name="firm" id="user_companyname" style="color:#888" size="35" placeholder="Firmenname"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" ><br><br>
<input type="submit" name="submitbutton" id="submit" value="Kostenlos registrieren">
</form>
</div>
<div class="register-terms">
<p>Mit der Registrierung stimmen Sie den Datenschutzbestimmungen und den AGB zu.</p>
</div>
</div>
First of all it is not recommended to place the form and the processor page on the same page to void redundant insert via refresh. However, in the processor section you have to use any mean of redirect after any end of the process, in your code die() and echo should be replaced with the redirect with a parameter of pre specified message. for instance, you have four ends in your processor, so your code should look like:
<?php
$conn = mysqli_connect("localhost","root","");
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($conn, 'registration');
if(isset($_POST['submitbutton'])){
if ($_POST['password'] == $_POST['confirm_password']) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$firm = mysqli_real_escape_string($conn, $_POST['firm']);
$check_email_exists = mysqli_query($conn, "SELECT email FROM users WHERE email = '$email'");
$count = mysqli_num_rows($check_email_exists);
if ($count == 0) {
$sql = "INSERT INTO users(email, password, gender, fname, lname, firm) VALUES('$email', '$password', '$gender', '$fname', '$lname', '$firm')";
if(mysqli_query($conn, $sql)){
header("Location: user_login.php?msg=1");
exit();
} else{
header("Location: user_login.php?msg=2");
exit();
}
// close connection
mysqli_close($conn);
} else {
header("Location: user_login.php?msg=3");
exit();
}
}
else {
header("Location: user_login.php?msg=4");
exit();
}
}
$msg = [
"Records added successfully.",
"SQL Error",
"Email exists, Please use a different email",
"Passwords not matching, please try again"
];
if (isset($_GET['msg']) && isset($msg[($_GET['msg']-1)])){
$message = $msg[($_GET['msg']-1)];
}
// In your form
....
</div>
<?php if (isset($message)): ?>
<div class="message"><?=$message;?></div>
<?php endif; ?>
<div class="user-login">
<form class="login-form....
In above scenario, submit the form page itself using
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
But make registration html to php file
<?php
if(isset($_POST['submitbutton'])){
//perform validation, display error if any
}
?>
If you want to go modular approach then use class having validate, register method after submit include class file and use methods
For each error message make a variable $message="Password not matching..." and then after <div class="user-login"> you can put:
<?php echo "<p>$message</p>"; ?>
Remember to create a blank $message="".
Hope it helps.
Hi I'm trying to do a form with data validation before writing into database. But im not sure why the data validation is not working. Below is my codes
filename: bookoffer.php
$NameErr = $EmailErr = $DescriptionErr = "";
//$Name = $Email = $Description;
if (isset($_POST['Submit']))
{
$errors = array();
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
}
else
{
$Name = ($_POST['Name']);
//check if name only contain letter and white space
if (!preg_match("/^[a-zA-Z ]*$/",$Name))
{
$NameErr = "**Only letters and white space allowed**";
}
}
if (empty($_POST['Email']))
{
$EmailErr = "**Email is required**";
}
else
{
$Email = ($_POST['Email']);;
//check if e-mail address is well-formed
if (!filter_var($Email, FILTER_VALIDATE_EMAIL))
{
$EmailErr = "**Invalid email format**";
}
}
if (empty($_POST['Description']))
{
$Description = "**Description is required**";
}
else
{
$Description = ($_POST['Description']);
}
}
//if(count($errors)==0)
include 'database_connect.php'; //make database connection
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Description = $_POST['Description'];
$sql = "INSERT INTO books_offer (Name, Email, Description) values ('$Name', '$Email', '$Description')";
$redirect = true;
header('Location: Thank_you.php');
mysqli_query($conn, $sql) or die (mysqli_error($conn));
mysqli_close($conn);
?>
Here is the html file which is calling for bookoffer.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Please Offer Your Book</h2>
<form id="bookoffer" method="post" action="bookoffer.php" >
<p><span class="error"> <font color="red">*required field.</font></span></p>
Name<font color="red">*</font> <input type="text" name="Name" >
<span class="error"> <?php echo $NameErr;?></span>
<br></br>
Email<font color="red">*</font> <input type="text" name="Email" >
<span class="error"> <?php echo $EmailErr;?></span>
<br></br>
Description<font color="red">*</font><textarea name ="Description" rows="5" cols="40" ></textarea>
<span class="error"> <?php echo $DescriptionErr;?></span>
<br></br>
<input type="submit" name="submit_form" value="Submit" />
</form>
</body>
</html>
You're not populating your $errors array so the if statement you've commented out will always be true. You are storing your errors in individual variables. One option would be to change
$errors = array();
to
$errors = false;
then, when you are setting the error variables add a line to each one to set $errors to true, one example,
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
$errors = true; // this line added
}
You can now update your commented out if statement to
if ($errors) {
I have a from to introduce the data and I'm trying to validate the data. However, either the data is introduced or not, the info is introduce in the database.
For example, If I leave the name blank, I get an error message that the name cannot be blank, but the blank name is introduce in the database.
How can I do, so only after all the fields have been validated, the data is introduce in the database?
Thank you so much
CODE
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = "";
$name = $email = $surname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["surname"])) {
$surname = "";
} else {
$surname = test_input($_POST["surname"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Last Name: <input type="text" name="surname">
<span class="error"><?php echo $surnameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $surname;
echo "<br>";
?>
<?php
$db = pg_connect('host=localhost dbname=postgres user=myusername password=mypassword');
$firstname = pg_escape_string($_POST['name']);
$surname = pg_escape_string($_POST['website']);
$emailaddress = pg_escape_string($_POST['email']);
$query = "INSERT INTO friends(firstname, surname, emailaddress) VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
?>
</body>
</html>