How to avoid duplicate input and empty input? - php

This would be a piece of my code.
$name = $_POST['UserNames'];
$pw = sha1($_POST['Passwords']);
$mail = $_POST['Emails'];
$pc = $_POST['Postcodes'];
$status = "0";
mysql_query("INSERT INTO userinfo
(Username,Password,Email,Postcode,status,valid)
VALUES
('$name','$pw','$mail','$pc','$status','$validate')
");
How do i make sure every input will not be null and the Email will never repeat.

Try this,
mysql_query("INSERT INTO userinfo (Username,Password,Email,Postcode,status,valid) VALUES ('$name','$pw','$mail','$pc','$status','$validate') ON DUPLICATE KEY UPDATE status='0'");
For more details refer, https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

use the empty function for the post fields to check if it contains something.
for the email, you must use a UNIQUE clause in your database for this field

About the email: set up the column of Email in userinfo table to be unique, and on insert just do on duplicate ignore
About the fields, well in the way you are working just do isset($_POST['XXX']) && !empty($_POST['XXX']). A better way would be working with some input validation class, like this one.

For empty input you can do the following :
$name = (isset($_POST['UserNames']) && !empty($_POST['UserNames'])) ? $_POST['UserNames'] : FALSE;
For duplicate email check you need to do a SELECT query before executing the INSERT statement.

First check values before mysql query:
$valid = true;
foreach($_POST AS $key=>$value)
{
if($value == null){
echo "Please provide ".$key;
$valid = false;
}
}
if($valid == true)
{
// check if email is in DB
$result = mysql_query("SELECT email FROM user info WHERE Email = '".addslashes($_POST['email'])."'");
if(mysql_num_rows($result) == 1)
{
echo "Email is already registered in our DB";
}
else
{
mysql_query("INSERT INTO userinfo (Username,Password,Email,Postcode,status,valid) VALUES ('$name','$pw','$mail','$pc','$status','$validate')");
}
}

Related

Save button that can also update once the record is already saved on the database

I was wondering how to construct the correct syntax for the if-else statement, or if there's something missing in my code.
<?php
include "../dbcon.php";
session_start();
ob_start();
$sql = mysqli_query($con,"SELECT * FROM clientdocuments WHERE docID = $_POST[docID]");
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
//IF CSS input value is filled
if(!empty($_POST)){
$output = '';
$message = '';
$docID = mysqli_real_escape_string($con, $_POST["docID"]);
$docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]);
//I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
if(isset($_POST["docID"])){
if (!empty($docID)) {
$query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE
} else {
$query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
}
$str = mysqli_query($con,$query);
if(!$str){
echo 'FAILED';
}
}else{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
}
}
?>
remove this if statment: if (!empty($docID)) {
Make sure that u send with each post update the "docID" value
if(isset($_POST["docID"])) statement checks to see whether the input with the name docID has a value.
if(!empty($_POST)) I am not sure whether this will work, my guess is that you are trying to check whether the request method is POST (if the save button was clicked). For this I use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
I would then check to see whether docID has a value ie
(isset($_POST["docID"])) OR (!empty($_POST["docID"]))
Difference between isset and !empty
What's the difference between 'isset()' and '!empty()' in PHP?
If there is a value, $query would be the update statement
If there is no value $query would be the insert statement In this situation don't enter the DocID value (because then it would always be 0 which will also cause errors)
Hope that makes sense!

How to escape mysql blank and duplicate data using php

I am using this code to send data to mysql database and its functioning well though users are sending blank data and duplicating too.
<?php
require "conn.php";
$lostidno = $_POST ["lostidno"];
$phonenol = $_POST ["phonenol"];
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
?>
How do I prevent this?
You can use trim function to remove spaces at the beginning and the ending of a string. After that you are able to check if the two parameters aren't empty:
<?php
require "conn.php";
$lostidno = trim($_POST["lostidno"]);
$phonenol = trim($_POST["phonenol"]);
if(!empty($lostidno) && !empty($phonenol))
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE) {
echo "Information Recieved!";
}
else {
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
}
$conn->close();
}
?>
You should also have a look at this to prevent SQL injections.
1. To avoid blank values
Check the values of variables before executing insert query on database using empty() PHP function.
2. Avoid duplicate values
You can do it in two ways, Either specify UNIQUE constriant in database TABLE or run SELECT query before inserting data into database.
//this to check the duplicate records
Fire the select query : select * from lostdb.lost where col1= $lostidno and col2 = $phonenol;
//this is to check the blank condition
if($lostidno !== "" && $phonenol != "")
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
}
The best way to prevent duplicates is to mark the unique database columns as UNIQUE
ALTER TABLE <table_name> ADD UNIQUE(<column_name>);
To prevent blank data from ever getting into the database you need to check them with a few modifications in the code you posted:
if( ($lostidnol != "") && ($phonenol != "") )
{
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
{
//error
}
}
else
{
//Notify the user that they're trying to insert blanks
}
If you want to provide proper user experience you should also provide some client side validation using JavaScript or jQuery
Use trim function to remove blank spaces from string.
<?php
require "conn.php";
$lostidno = trim($_POST ["lostidno"]);
$phonenol = trim($_POST ["phonenol"]);
//Check record exist or not.
$unique_check = "select count(*) as cnt from lostdb.lost where lostidno='".$lostidno."' and phonenol='".$phonenol."'";
//Execute above query and check record already exist or not. If record not exist then only allow to insert it.
$result_unique_check = $conn->query($mysql_qry)->one();
$record_exist = $result_unique_check['cnt'];
if($record_exist > 0){
echo "Record alreay exist.";
}else{
//Insert new record
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
}
?>

Check if activation_code is not activeted at login. "ONLY" activation_code

This is the code I use at login:
$q = $lacz->query("SELECT email, pass, activation_code
FROM users
WHERE email='". $nazwa_uz_l ."'
AND pass = '". $haslo_l ."'
AND activation_code IS NULL ");
if($q->num_rows>0) {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l; }
else
{
echo 'Pass or Log are wrong, or activation code is not confirmed (check email).';
exit;
}
In this query I check for all 3 things: email, password and activation code, and then output an error. What I want to do is to output an first error when Pass or Log are wrong and second error (something like elseif) when activation code IS not NULL. I tried else if and two queries, but I was getting the errors. Can You help me? I check the answers and give points, thanks.
Remove "AND activation_code IS NULL" from your query and do something like
if($q->num_rows>0)
{
$row = $q->fetch_assoc();
if(!is_null($row['activation_code']))
{
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
}
else
{
echo 'Activation code is not confirmed (check email).';
exit;
}
}
else
{
echo 'Pass or Log are wrong.';
exit;
}
Don't check the activation code in the query. Just get the user information, along with the activation code field:
SELECT email, pass, activation_code
..
WHERE email='foo' and pass='bar'
Then you can test the individual conditions in your code:
if (number_of_rows == 0) {
... bad username/password
} else if ($activation_code == '') {
... code is blank/null
}
If you remove the AND activation_code IS NULL from the query's WHERE clause, you'll be able to pull data for a user matching the given email/password. Then, with that, you'll be able to determine if the user exists, or if their activation code is empty:
$q = $lacz->query("SELECT email, pass, activation_code
FROM users
WHERE email='". $nazwa_uz_l ."'
AND pass = '". $haslo_l ."'");
if ($q->num_rows === 0) {
echo 'Password or email address are wrong.';
exit;
} else {
$row = $result->fetch_assoc();
if (empty($row['activation_code'])) {
echo 'Activation code is not confirmed.';
exit;
} else {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
}
}
Side-note (not answer related): I highly suggest using a parameterized query instead of directly inserting the values into the SQL; if you prefer the current way, make sure you're sanitizing the input first to prevent SQL Injection.

display message to let user know that the value already exist

I want to display an error message if the insert already exists.
I've made name unique in the database and if I enter the same value, it does not insert. Just as I wanted. Here is my code:
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
Now I want to echo a message to let the user know that the value he has entered is already present in the database and will not be inserted. Anyone?
I take it you are collecting $foo from a form?
what I would do is an sql query of the table register collecting the name field then when you collect the name entered in the form and its posted you can run an if condition against the name field you have already gathered using the sql statement and if there is a name = to the name they enter on the field they can receive a message and exit before the sql injection into the register table.
The simpliest way:
$res = mysql_query($query):
if ($res)
echo 'Insertion ok';
else
echo 'error: name already exists';
A better way: do first a SELECT query to see if name exists or not.
Note: you should think about moving from mysql_* to mysqli_* or PDO
Try this :
$query = "INSERT INTO register(name) VALUES('$name')";
$user = mysql_query($query):
if ($user)
echo 'User Register';
else
echo 'User Already Exist';
As per Melon's comment, you should use mysqli.
// Create your connection
$mysqli = new mysqli($host, $user, $pass, $dbname);
// Do your query
$mysqli->query("INSERT INTO register(name) VALUES('$foo')");
if($mysqli->affected_rows == 0) {
// Your chosen method of alerting the user goes here
}
\\this first part collects name information from your table.
$name="SELECT name FROM register";
$name_query = mysqli_query($db_conx, $name);
$numrows = mysqli_num_rows($name_query);
if($numrows < 1){
echo "cannot find user";
header ("location: index.php");
}
while ($row = mysqli_fetch_array($name_query, MYSQLI_ASSOC)){
$name = $row["name"];
}
\\ this part gets the name from your form
if (isset($_POST['class']) && ($_POST['class'] !='')){
$foo = $_POST['foo'];
\\this part checks to see if the 2 values are equal
if ($name == $foo){
echo "This name has already been used try again";
\\this part then adds the name if its not already in the database
}else{
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
}
}
//then all you need to do is create your form to post the foo or name so it can be collected and passed through the querys.

I don't know what's wrong with this code SQL

I'm new to PHP and Mysql, for some reason it only checks for statement if($email == $result2 ) wether the input is username or email. I don't know why? can someone explain it logically, i'm stuck for hours figuring it out. :( Thanks Please be kind.
<?php
session_start();
include_once("connect.php");
$email = $_POST['email'];
$username = $_POST['username'];
//echo $_POST['email'];
if(isset($_POST['email']) )
{
$extract= mysql_query("SELECT username, email FROM users");
$resultq = mysql_num_rows($extract);
while($row= mysql_fetch_array($extract))
{
$result = $row['username'];
$result2 = $row['email'];
//$pass = $_POST['pass'];
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
exit(); //break;
}
if ($username == $result )
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
exit(); //break;
}
else
{
}
}
}
It's behaving as written. If either if() test succeeds, you tell the script to exit().
Remove the exit() calls...
You also really REALLY need to learn about WHERE clauses in queries. You are sucking across your entire user table and comparing the records one at a time. This is the equivalent of driving to the grocery store, buying up the ENTIRE store's inventory, driving it home... then throwing it all in the garbage because all you really wanted was one candy bar.
I think you better use unique in your email and username column, then you don't need to check it anymore, mysql will do that for you!
Does it go into the second if statement ( if ($username == $result ) ) after you comment out the first one ( if ($username == $result )) ?
If so, then it keeps hitting that exit() function.
Guys i kinda guessed the answer from combining some of your comments. for some reason i need to include isset($_POST['username']) along with isset($_POST['email']) in order for my if Statements to be all executed... perhaps it was the isset checking if there is a value for username.
try this
if($email == $result2 )
{ //check if there is already an entry for that username
echo "Email Address is already used!";
//---------removed that line
}
else if ($username == $result ) //add else if instead of if
{
echo " Username is already Taken!";
//mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
//header("location:index.php");
//----------removed that line
}
else
{
}
EDIT:
change this
if(isset($_POST['email']) )
to
if(isset($_POST['email']) or isset($_POST['username']))
this to check them both. you are checking just email thats why you dont get the second if.
change this line the following line:
$extract= mysql_query("SELECT username, email FROM users");
Then use where clause as follows:
$extract= mysql_query("SELECT username, email FROM users where username='$username' and email='$email'");

Categories