MySQL Insert occurs twice on one submit - php

I have this PHP file that handle's users input to signup using mysql... I have a problem with it that makes the users input be entered twice... So, this was only one input into the signup form. Below is about half of my signup form (the most useful part)...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require("db-settings.php");
// Security
if (empty($_POST['name'])) {
echo "Sorry, fullname input was empty, please retry if you like.";
die();
} else {
$fullname = $_POST['name'];
}
if (empty($_POST['email'])) {
echo "Sorry, email input was emty, please retry if you like.";
die();
} else {
$email = $_POST['email'];
}
if (empty($_POST['password'])) {
echo "Sorry, password was empty, please retry if you like.";
die();
} else {
$password = $_POST['password'];
// If password variable is success to set, let's encrypt it now!
$password = password_hash($password, PASSWORD_DEFAULT)."\n";
}
// Log users IP and store in variable
$ip = $_SERVER["REMOTE_ADDR"];
// Create connection
$conn = new mysqli($servername, $username, $db_password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
$stmt->execute();
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
So, with all this here. I will also give the entire form section in the html code below...
<form action="signup.php" method="post">
<h1>Sign up</h1><br/>
<span class="input"></span>
<input type="text" name="name" placeholder="Full name" title="Format: Xx[space]Xx (e.g. John Doe)" autofocus autocomplete="off" required pattern="^\w+\s\w+$" />
<span class="input"></span>
<input type="email" name="email" placeholder="Email address" required />
<span id="passwordMeter"></span>
<input type="password" name="password" id="password" placeholder="Password" title="Password min 10 characters. At least one UPPERCASE and one lowercase letter" required pattern="(?=^.{10,}$)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/>
<button type="submit" value="Sign Up" title="Submit form" class="icon-arrow-right"><span>Sign up</span></button>
</form>
So, there must be something in the code that makes it enter in twice... Plus, how do I reset the id numbers? Cause every time I make a new user, and this happens (which is every time) then I just delete the users and it still counts as though they still exist.

It's because of this line. You don't need to put an if else statement.
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
}
Simply do this-
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
//Set the variables here for $fullname, $email, $password and $ip
if($stmt->execute())
{
echo "New user was created successfully, please wait for activation...";
}
else { echo "There was a problem";}
$stmt->close();
$conn->close();
UPDATE
For the id part, I assume you are using auto increment but I would suggest you to insert them manually instead of relying on it. I would suggest you to use a unique key derivation function and encoding them (in case you would prefer them to be plaintext and using them as IDs).
If you want to track how many entries are in there, you can always count the number of rows with mysqli_num_rows().

You used both execute() and query(), thus executing twice.
Firstly, it inserted 1 row at $stmt->execute();. Then it inserted another row at $conn->query($sql).
$stmt->execute();
if ($conn->query($sql) === TRUE) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You should only $stmt->execute();:
if ($stmt->execute()) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note:
It's a better practice is to stick with prepared statements and use execute() for increased security rather than using $conn->query($sql). More information of the difference at PDO's query vs execute.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
require("db-settings.php");
// Security
if (empty($_POST['name'])) {
echo "Sorry, fullname input was empty, please retry if you like.";
die();
} else {
$fullname = $_POST['name'];
}
if (empty($_POST['email'])) {
echo "Sorry, email input was emty, please retry if you like.";
die();
} else {
$email = $_POST['email'];
}
if (empty($_POST['password'])) {
echo "Sorry, password was empty, please retry if you like.";
die();
} else {
$password = $_POST['password'];
// If password variable is success to set, let's encrypt it now!
$password = password_hash($password, PASSWORD_DEFAULT)."\n";
}
// Log users IP and store in variable
$ip = $_SERVER["REMOTE_ADDR"];
// Create connection
$conn = new mysqli($servername, $username, $db_password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `table-ex` (fullname, email, password, ip) VALUES ('$fullname', '$email', '$password', '$ip')";
$stmt = $conn->prepare($sql);
//$stmt->bind_param('sss', $fullname, $email, $password, $ip);
if ($stmt->execute()) {
echo "New user was created successfully, please wait for activation...";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$conn->close();

Related

MYSQL is automatically decrypting my password upon record entry

I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>

Empty fields can get inserted into my database

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

Inserting E-mail Into DB

Trying to build an email list in a database. I made this code, but it's not working and i'm not getting any errors. Am I on the right track?
HTML:
<div id="signup">
<h1>Sign-Up For Our Newsletter!</h1>
<form method="post" action="scripts/php/addSubscription.php">
<label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
</form>
</div>
PHP:
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo 'Sorry, An error occured. Please try again.';
}
mysqli_close($conn);
$conn is a variable in mysqli_connect.php
Adding contents of mysqli_connect.php just for reference:
<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>
I use this on several databases and it connects each time.
EDIT:
Updated code per answers/comments and still nothing is happening.
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
SOLVED:
require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
You are currently getting an error but your code doesn't show you. Print the error for a start:
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
The real error you are getting is a syntax error. This is how your generated SQL looks like:
INSERT INTO newsletterusers (email) VALUES (hello#email.com)
Note that there are no quotes around it, you can fix it by surrounding $email with quotes:
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";

user is already taken?

I have this code:
$username = $_POST["username"];
$password_input = $_POST["password"];
$password = md5($password_input);
$email_input = $_POST["emailaddress"];
$email = md5($email_input);
if (!($stmt = $con->prepare("INSERT INTO `users` (`username`,`password`,`email_address`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User has been Created! Feel free to login - <a href='login.php'><span class='button color_blue'>Login</span></a>";
Within the SQL database an email/username can only be used once (UNIQUE) and I wondered if there was a way to change the echo to only appear if the data was successfully added and then a different message for if it wasn't successful.
Thanks - I'm still a rookie!
EDIT: so after using some code from the answer i am now at:
$username = $_POST["username"];
$password_input = $_POST["password"];
$password = md5($password_input);
$email_input = $_POST["emailaddress"];
$email = md5($email_input);
if (!($stmt = $con->prepare("INSERT INTO `users` (`username`,`password`,`email_address`) VALUES (?,?,?)")) || !is_object($stmt)) {die( "Error preparing: (" .$con->errno . ") " . $con->error);}
$stmt->bind_param('sss', $username, $password, $email);
$stmt->execute();
$stmt->close();
if ($con->affected_rows == 1) {echo "User has been Created! Feel free to login - <a href='login.php'><span class='button color_blue'>Login</span></a>";}
var_dump($con->affected_rows);
successful and unsuccessful INSERTS for some reason all have -1 as their "affected rows" output
The execute() method returns true if successful.
Replace:
$stmt->execute();
with:
if($stmt->execute()) {
echo "user created!";
} else {
echo "error: " . $stmt->error;
}
Yes, you just have to check if the query was successful or not:
change the end of your code by this:
$success = $stmt->execute();
$stmt->close();
if ($success)
echo "User has been Created! Feel free to login - <a href='login.php'><span class='button color_blue'>Login</span></a>";
else
echo "Impossible to create that user: ".$stmt->error;
To provide many different messages I work with flags. Simply say: if the username equals an existing db name, userExistMsg = 1.
To check if the User Exists, simply use a SELECT query in sql and ask for any entrys on the given user. This query should result in none obkects if the username is free.
Btw. You seem to use simple md5 for pw encoding. That's not verry secure. Better use something like salted passwords.
To check for successful UPDATE/INSERT/DELETE query, you would need to check if returned affected rows are more than zero.
http://php.net/mysqli_affected_rows
Returns the number of rows affected by the last INSERT, UPDATE,
REPLACE or DELETE query.
In your case:
if ($con->affected_rows == 1) {
echo "User has been Created! Feel free to login - <a href='login.php'><span class='button color_blue'>Login</span></a>";
}
Try this. This is a sample answer change this according to your code..
$username = $_POST["username"];
$password_input = $_POST["password"];
$password = md5($password_input);
$email_input = $_POST["emailaddress"];
$email = md5($email_input);
$con=mysqli_connect("HOST","USER","PASSWORD","your_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT COUNT(username) FROM users WHERE username = $username ");
$datacount2 = mysql_num_rows($result );
if($datacount2 < 1)
{
if (!($stmt = $con->prepare("INSERT INTO `users` (`username`,`password`,`email_address`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $username, $password, $email);
$stmt->execute();
$stmt->close();
if($stmt)
{
echo "User has been Created! Feel free to login - <a href='login.php'><span class='button color_blue'>Login</span></a>";
}
else
{
echo "Insert Failed";
}
}
else
{
echo "User already exists..";
}
You could use mysqli_stmt::affected_rows to find out if rows were affected. If not, you can print out your error message

Stop empty values from input boxes from being inserted into my database? PHP

This is the html form (register.php):
<html>
<body>
<form action="handle_registration.php" method="post">
<fieldset><legend>Enter your
information in the form below:</legend>
First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">
</form>
</body>
</html>
This is the php script that handles the registration (handle_registration.php):
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Make sure all of the input boxes have a value:
if (empty($fname)) {
die('You forgot to enter your first name!');
}
if (empty($lname)) {
die('You forgot to enter your last name!');
}
if (empty($uname)) {
die('You forgot to choose a username!');
}
if (empty($pword)) {
die('You forgot to choose a password!');
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
?>
Here's the problem:
I want to submit the entered values into my database if all of the input fields have a value, but when I use the die function after checking to see if they're empty, then it kills the script. I just want to kill the part were it inserts it into my database if one or more of the fields are empty & display an error message that tells which field was empty. I'm not sure how to get around this and any help will be greatly appreciated.
The solution is rather simple. Just store the error message in a variable and before inserting rows into the DB - check weather the error is set or if it's empty. If it's empty - we can insert the row. Otherwise - let's show the error message.
// Currently we do not have an error
$error = NULL;
// Validate
if (empty($pword)) {
$error = 'You forgot to choose a password!';
}
// If there are no errors - lets insert
if (!$error) {
$sql = 'INSERT INTO ...';
}
DOn't use die ,use some variable to store errors and print them later
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname']; $lname = $_POST['lname']; $uname =
$_POST['uname']; $pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name =
"registration_info"; $con = mysqli_connect("$db_host", "$db_user",
"$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ()) { echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }
// Make sure all of the input boxes have a value:
if (empty($fname)) { $error_msg[]='You forgot to enter your first name!'; }
if (empty($lname)) { $error_msg[]='You forgot to enter your last name!'; }
if (empty($uname)) { $error_msg[]='You forgot to choose a username!'; }
if (empty($pword)) { $error_msg[]='You forgot to choose a password!'; }
// Insert the data from the form into the DB:
if(count($error_msg)==0){
$sql = "INSERT INTO basic_information (First_Name, Last_Name,
Username, Password) VALUES ('$_POST[fname]', '$_POST[lname]',
'$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
else { echo "Record has been added"; }
// Close the connection:
mysqli_close($con);
}else{
print_r($error_msg);
}
?>
Full working example to stop insertion of empty data
<?php
if (isset($_POST["submit"])) {
$emptyInput = NULL;
if (!($_POST["firstname"] == $emptyInput or $_POST["lastname"] == $emptyInput or $_POST["email"] == $emptyInput)) {
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["email"] . "')";
if (mysqli_query($conn, $sql)) {
echo 'Record inserted successfully!';
}
} else {
echo 'all fields are compulsory!';
}
}
?>
You could use a $errors variable to hold the errors with all the fields
$error = array();//initializing the $error
if (empty($fname)) {
$error[] = 'You forgot to enter your first name!';
}
if (empty($lname)) {
$error[] = 'You forgot to enter your last name!';
}
if (empty($uname)) {
$error[] = 'You forgot to choose a username!';
}
if (empty($pword)) {
$error[] = 'You forgot to choose a password!';
}
if(!empty($error))//if error occured
{
die(implode('<br />', $error));//Stops the script and prints the errors if any occured
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);

Categories