so my php validation has two check functions, first it checks for an empty name or password entry and second if user enters unwanted characters while entering his name, the problem is that if the user does enter an unwanted character or numbers in the 'name' entry the form is still saved to the database which it should not, nothing is saved to the database if the users leaves both the name and password field empty and the error is shown, which means half of my validation check is working fine . can any one help me out ?
<?php
// Connect to data base
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$nameErr = $userpasswordErr = "";
$name = $userpassword = "";
//check for error
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//validate name and password
if (
empty($_POST["name"]) ||
empty($_POST["userpassword"] ||
!preg_match("/^[a-zA-Z ]*$/",$name))
) {
$nameErr= "* Incorrect username or password ";
} else {
$name = test_input($_POST["name"]);
$userpassword = test_input($_POST["userpassword"]);
$sql = "INSERT INTO users(name,email)
VALUES ('$name','$userpassword')";
if ($conn->query($sql) === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<span class="error"></span>
<form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>">
name : <input type="text" name="name" value="<?php echo $name;?>"/>
<span class="error"><?php echo $nameErr ;?> </span>
<br/><br/>
password : <input type="text" name="userpassword" value="<?php echo $userpassword ; ?>">
<span class="error"><?php echo $userpasswordErr ;?> </span>
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
The $name in regular expression check should be $_POST['name']
if(empty($_POST["name"]) || empty($_POST["userpassword"] || !preg_match("/^[a-zA-Z ]*$/",$_POST["name"])))
{
$nameErr= "* Incorrect username or password ";
}
Related
registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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 = "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["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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 = "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["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<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
<input type="radio" name="gender" value="other">Other
<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 $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
index.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {
color:red;
}
</style>
</head>
<body>
<?php
// define variables and set to empty values
include_once 'connect.php';
$nameErr = $emailErr = $usernameErr = $passwordErr = $DateOfBirthErr = $departmentErr = $ageErr = "";
$name = $email = $username = $password = $DateOfBirth = $department = $age = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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 = "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["username"])) {
$usernameErr = "username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "password is required";
} else {
$password = test_input($_POST["password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// check weather password is alphanumeric
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{6,}$/', $password)) {
$passwordErr = "Password must be alphanumeric and atleast 6 characters
long!";
}
}
if (empty($_POST["Date_of_birth"])) {
$DateOfBirthErr = "Date Of Birth is required";
} else {
$DateOfBirth = test_input($_POST["Date_of_birth"]);
}
if (empty($_POST["department"])) {
$departmentErr = "Department is required";
} else {
$department = test_input($_POST["department"]);
}
if (empty($_POST["age"])) {
$ageErr = "AGE is required";
} else {
$age = test_input($_POST["age"]);
}
if ($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "") {
$check = "SELECT * FROM users WHERE username = '$_POST[username]'";
$rs = mysqli_query($mysqli, $check);
$da = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($da[0] > 1) {
echo "Username Already in Exists<br/>";
}
else {
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,
`Date_of_birth` , `department` ,`age`)
VALUES ('','" . $username . "', '" . $hashed_password . "', '" . $email . "' ,
'" . $name . "' , '" . $DateOfBirth . "' , '" . $department . "' , '" . $age . "')";
if (mysqli_query($mysqli, $sql)) {
echo "Registered successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div style="padding-left: 250px">
<h2>Registration Form</h2>
<p><span class="error">All fields are required </span></p>
<form method="post" action="">
Name:
<input type="text" name="name" style="margin-left: 52px">
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email" style="margin-left: 48px">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
Username:
<input type="text" name="username" style="margin-left:26px">
<span class="error"> <?php echo $usernameErr;?></span>
<br><br>
Password:
<input type="password" name="password" style="margin-left:30px">
<span class="error"> <?php echo $passwordErr;?></span>
<br><br>
Date Of Birth :
<input type="date" name="Date_of_birth">
<span class="error"> <?php echo $DateOfBirthErr;?></span>
<br><br>
Age :
<input type="number" name="age" style="margin-left:62px">
<span class="error"> <?php echo $ageErr;?></span>
<br><br>
Department :
<select name="department" style="margin-left:14px">
<option value="EE">Electrical & Electronics</option>
<option value="EC">Electronics & Communication</option>
<option value="ME">Mechanical</option>
<option value="CS">Computer Science</option>
<option value="CV">Civil</option>
<option value="IS">Information Science</option>
</select>
<span class="error"> <?php echo $departmentErr;?></span>
<br><br>
<input type="submit" name="submit" value="Register">
</form>
</div>
</body>
</html>
connect.php
<?php
$databaseHost = 'localhost';
$databaseName = 'amith';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
?>
i'm creating a simple php registration form, i only have one issue which is not getting fixed i.e., when any one while registering enters the same username then an error message should throw saying that username already taken i have tried with the above code but its not working. please can any one help me to fix my issue.
before
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` ,
`name` , `Date_of_birth` , `department` ,`age`)
VALUES ('','".$username."', '".$hashed_password."', '".$email."' ,
'".$name."' , '".$DateOfBirth."' , '".$department."' , '".$age."')";
You can write SQL to check if username is exist or not :
SQL : 'SELECT username from users where username = $username';
If this query returns result with count more than 0 then show an error message as 'This Username already exists';
If it gives you 0 results then proceed with INSERT functionality.
Before you insert the new user you can query for the username with a select like:
SELECT username FROM users WHERE username='$username'
If this query returns more than 0 rows the username exists already.
Hi you can try like this
variable should be like this $_POST['username']
$sql = "INSERT INTO users(`id`,`username`, `password`, `email` , `name` ,`Date_of_birth` , `department` ,`age`) VALUES ('', ".$username.", ".$hashed_password.", ".$email." , ".$name." , ".$DateOfBirth." , ".$department." , ".$age.")";
An effective way to tackle this unique username problem is to validate the username at the time of entry from UI.
Step 1:in html input box there should be jquery or js function call to a php page with entered username as argument.
Step 2 the backend php scrpt will simple check the username in database and if exists the will return a JSON o/p that userbane alreasy exist else it will return true.
Step 3:show the message to on UI with simple Js and block further processing of form.
Also you must check the uniqueness of username after form submit and before insert into your data base table to avoid concurrent submit by two different user with same username.
Also if possible make sure username is primary key in your database table to avoid concurrent submit with same username problem,This will add another solid layer of protection at the bottom.
<input type="text" name="uname" id="uname" onblur="unameOnBlur(this.value);">
You can do it onkeyup or any suitable event also.
inside unameOnBlur make an ajax call like
$.ajax({
url: 'json_uname.php?uname=' + uname,
dataType: 'json'
}).done(function (j){
if(username unique)
//your action code
})
the above one is sample ajax call example
Json_uname.php page is simple to write to check against db.
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.
I am attempting to learn some html/php. I have created a form that i want to submit info to a MYSQL database. I have created the database and created the forms etc. The problem i have is that when the form is submitted it is submitting blank info to the table. If i replace the variables with "123" that is posted to the database so it seems to not be pulling the info from the index to the form. Cannot work out why it is posting blank info, any suggestions? My index page is :
<html>
<head>
<style type="text/css">
.sms_image
{
text-align: right-side;
}
</style>
<script src="//www.powr.io/powr.js" external-type="html"></script>
<div class="powr-hit-counter" id="b6cbafa4_1487845849" align="right-side" </div>
<p class="sms_image"><img src="http://images.knowledge- action.co.uk/sites/default/files/sms_logo_short_0.jpg" height="100" width="170"> </img><br></p>
<title> Simply Mail Solutions </title>
</head>
<body background="https://media.licdn.com/media/AAEAAQAAAAAAAAYCAAAAJDQ1YTQ0MTNlLWI2MD ItNGYxOS05MjMxLWFmOTZhNjgyMjNhMA.png">
<font color="white">Welcome to a random test page</font>
<br>
<br>
<form action="yourform-processor.php" name="FirstAttempt" method="POST" enctype="text/plain">
<font face="impact" color="white">Client ID:</font>
<input type="text" name="client_id" ><br>
<br>
<font face="impact"color="white">Domain:</font>
<input type="text" name="domain"><br>
<br>
<font face="impact" color="white">Comments:</font>
<input type="textarea" name="comment" style="width: 568px; height: 273px"> <br>
<br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
<br>
<br>
</form>
<footer>
<p>Posted by: Dylan Cunliffe</p>
</footer>
</body>
</html>"
My PHP form that posts to the database is:
<?php
$servername = "localhost";
$username = "Dylanc";
$password = "xxx";
$dbname = "FirstAttempt";
$errors = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//first validate user input
if (empty($_POST['client_id'])) {
echo "enter client id";
$errors++;
} else {
$client_id = $_POST["client_id"];
}
if (empty($_POST['domain'])) {
echo "enter domain";
$errors++;
} else {
$domain = $_POST["domain"];
}
if (empty($_POST['comment'])) {
echo "enter comment";
$errors++;
} else {
$comment = $_POST["comment"];
}
if ($errors <= 0) {
//fields are not empty save to db
$sql = $conn->prepare("INSERT INTO FirstAttempt (client_id,domain,comment) VALUES(?,?,?) ");
$sql->bind_param("ssss", $client_id, $domain, $comment);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//report bacck the error
}
}
$conn->close();
?>
Any suggestions would be greatly appreciated.
Best and simple clean solution use mysqli prepared statments, or use pdo prepared statements.
MYSQLI Prepared :
<?php
$servername = "localhost";
$username = "Dylanc";
$password = "xxxx";
$dbname = "FirstAttempt";
$errors = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//first validate user input
if (empty($_POST['client_id'])) {
echo "enter client id";
$errors++;
} else {
$client_id = $_POST["client_id"];
}
if (empty($_POST['domain'])) {
echo "enter domain";
$errors++;
} else {
$domain = $_POST["domain"];
}
if (empty($_POST['comment'])) {
echo "enter comment";
$errors++;
} else {
$comment = $_POST["comment"];
}
if ($errors <= 0) {
//fields are not empty save to db
$sql = $conn->prepare("INSERT INTO FirstAttempt (client_id,domain,comment) VALUES(?,?,?) ");
$sql->bind_param("ssss", $client_id, $domain, $comment);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//report bacck the error
}
}
$conn->close();
?>
with PDO prepared statements
<?php
$servername = "localhost";
$username = "Dylanc";
$password = "xxxx";
$dbname = "FirstAttempt";
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO($dsn, $username, $password, $opt);
//first validate user input
//first validate user input
if (empty($_POST['client_id'])) {
echo "enter client id";
$errors++;
} else {
$client_id = $_POST["client_id"];
}
if (empty($_POST['domain'])) {
echo "enter domain";
$errors++;
} else {
$domain = $_POST["domain"];
}
if (empty($_POST['comment'])) {
echo "enter comment";
$errors++;
} else {
$comment = $_POST["comment"];
}
if ($errors <= 0) {
$stmt = $conn->prepare("INSERT INTO FirstAttempt(client_id, domain, comment) VALUES(?,?,?)");
if ($stmt->execute(array(
$client_id,
$domain,
$comment
))) {
echo "New record created successfully";
} else {
// error in your code.
}
}
?>
NB: If we want to insert any data from external sources (like user input), it is very important that the data is sanitized and
validated.
Update :
<form action="yourform-processor.php" name="FirstAttempt" method="POST">
<font face="impact" color="white">Client ID:</font>
<input type="text" name="client_id" ><br>
<br>
<font face="impact"color="white">Domain:</font>
<input type="text" name="domain"><br>
<br>
<font face="impact" color="white">Comments:</font>
<input type="textarea" name="comment" style="width: 568px; height: 273px"> <br>
<br>
<input type="submit" value="Send" name="submit">
<input type="reset" value="Reset">
<br>
<br>
</form>
yourform-processor.php
<?php
$servername = "localhost";
$username = "Dylanc";
$password = "xxx";
$dbname = "FirstAttempt";
$errors = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
//first validate user input
if (empty($_POST['client_id'])) {
echo "enter client id";
$errors++;
} else {
$client_id = $_POST['client_id'];
}
if (empty($_POST['domain'])) {
echo "enter domain";
$errors++;
} else {
$domain = $_POST['domain'];
}
if (empty($_POST['comment'])) {
echo "enter comment";
$errors++;
} else {
$comment = $_POST['comment'];
}
if ($errors <= 0) {
//fields are not empty save to db
$sql = $conn->prepare("INSERT INTO FirstAttempt (client_id,domain,comment) VALUES(?,?,?) ");
$sql->bind_param("ssss", $client_id, $domain, $comment);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//report bacck the error
}
}
$conn->close();
}
?>
im just askin how to create a form that will save the input in the $_post thingy into the table much appreciated thanks!! or can you help me fix this code or create a new one to work please? i need your help please thanks again!
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "tsukishiro";
$id = $_POST['id'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$input = $_POST['input'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO connection(ID, name, comment, input) VALUES ('null', '$name', '$comment', 'input')";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["input"])) {
$input = "";
} else {
$input = test_input($_POST["input"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo "<input type='text' name='id'>";<br><br>
echo "<input type='text' name='name'>";
echo "<input type='text' name='comment'>";
echo "<input type='text' name='input'>";
echo "<input type='submit' name='submit'>";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>`
You miss $ sign for input variable
$sql = "INSERT INTO connection(ID, name, comment, input) VALUES ('null', '$name', '$comment', '$input')";
Add the <form> tag.
<form name="form_name" action="your_page.php" method="post">
<input type='text' name='id'>
<input type='text' name='name'>
<input type='text' name='comment'>
<input type='text' name='input'>
<input type='submit' name='submit'>
</form>
Updated:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "tsukishiro";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$input = $_POST['input'];
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["input"])) {
$input = "";
} else {
$input = test_input($_POST["input"]);
}
$sql = "INSERT INTO connection(ID, name, comment, input) VALUES ('null', '$name', '$comment', 'input')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<form name="form_name" action="" method="post">
<input type='text' name='id'>
<input type='text' name='name'>
<input type='text' name='comment'>
<input type='text' name='input'>
<input type='submit' name='submit'>
</form>