Why is this code to check duplicate usernames not executing properly? - php

$conn properly connects to the database.
The users table of the database consists of the following fields id,name, email, username and password. One of the entries in the table contains benedict as the value for the username.
Code:
$userslist = $conn->prepare("SELECT * FROM users WHERE username=?");
$userslist->bind_param("s",$user);
$usersresult=$userslist->execute();
if($userslist->num_rows>0)
{
$userErr="Username already exists";
$errors++;
}
Problem:
When I enter a username(which is being stored in $user) with benedict as the value, the code does not detect duplicate id in spite of already having such a username. Further, $userslist->num_rows when printed shows 0.
On the contrary the following code correctly identifies, that a duplicate id already exists and prints the errror. (this proves there is no connection error or table errors)
$query="SELECT * FROM users WHERE username='".$user."'";
$qresult=mysqli_query($conn,$query);
if($qresult->num_rows>0)
{ $userErr="Username already exists";
$errors++;
}
I am aware that unique key and PDO is a better solution. But why it doesn't prints proper results while using prepared statements.

An affected rows result of: -1 indicates the query returned an error and therefore wasnt executed.
Check your query for errors in column/tables names etc.
Is your connection working?
Please try the following to debug:
$userslist = $conn->prepare("SELECT * FROM users WHERE username=?");
$userslist->bind_param("s",$user);
$usersresult=$userslist->execute();
print_r($conn->error);

Id suggest using PDO to start with, it is much safer for DB queries. http://php.net/manual/en/book.pdo.php . I would also suggest that you use a count for this and not a SELECT *. This is a wasteful check to see if a row exists, it will be more efficient by using a count.
You would do this using PDO like this.
$stmt = $db->prepare("SELECT count(1) FROM users WHERE username=?");
$stmt->execute(array($user));
$result = $stmt->fetch();
if($result)
{
if($result[0] == 1) echo "Username already taken";
else "username free";
}
else
{
echo "error";
}

You could do something like this.
if(mysqli_num_rows($userslist) > 0){
echo "username already exists"
}
check if row exists with mysql - similiar question

Have you tried:
$conn = new mysqli("localhost","user","password","db");
$sql = "SELECT * FROM users where username='".$_POST['username']."'";
$result = $conn->query($sql);
$count = $result->num_rows;
if($count > 0)
{
echo "Username ".$_POST['username']." already exists!";
}

So error is not affected row: check why the query failed:
`
<?php
$userslist = $conn->prepare("SELECT * FROM users WHERE username=?");
$userslist->bind_param("s",$user);
$usersresult=$userslist->execute();
if($userslist->num_rows>0)
{
$userErr="Username already exists";
$errors++;
}
elseif($userlist->affected_rows == -1) {
echo 'An error occurred: ' . $conn->error;
}
?>
`
but you do realise, in the few milliseconds between the check and an actual insert, there might be an other user inserting that exact same name?
Added: how to do it when username is unique indexed:
<?php
$userslist = $conn->prepare("INSERT INTO users (username, name, etc) VALUES (?,?, ?)");
$userslist->bind_param("sss",$user, $name, $etc);
$usersresult=$userslist->execute();
if($conn->errno == 1062) {
$userErr="Username already exists";
$errors++;
}
elseif($conn->errno) {
echo 'An error occurred: ' . $conn->error;
}
else {
if($userlist->affected_rows == 1) {
echo 'success';
}
else {
echo 'unknown why not inserted';
}
}
?>

Related

get into the page only if the 2 $_post values [duplicate]

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result:
email no longer exists publisher#example.com
This is the code I'm currently using:
if (count($_POST)) {
$email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($dbl, $query);
if (is_resource($result) && mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
} else {
echo "email no longer exists" . $email . "\n";
}
}
Is there a better way to check if a row exists in MySQL database (in my case, check if an email exists in MySQL)?
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query)) which should have simply read as if (!$query).
I apologize for overlooking that mistake.
Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_ with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
Prepared statements are best to be used to help protect against an SQL injection.
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
FYI: Forms default to a GET method if not explicity instructed.
Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.
POST arrays are case-sensitive.
Consult:
http://php.net/manual/en/tutorial.forms.php
Error checking references:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/pdo.error-handling.php
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).
You must use the same one from connecting to querying.
Consult the following about this:
Can I mix MySQL APIs in PHP?
If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:
MySql php: check if Row exists
The mysql_* functions are deprecated and will be removed from future PHP releases.
It's time to step into the 21st century.
You can also add a UNIQUE constraint to (a) row(s).
References:
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
How to check if a value already exists to avoid duplicates?
How add unique key to existing table (with non uniques rows)
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = #Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.
PDO
PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
For more examples see: How to check if email exists in the database?
MySQLi
As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]
For more examples see: How to check whether a value exists in a database using mysqli prepared statements
Minor remarks
If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record

INSERT IGNORE, LIMIT 1... how to check if row exists before INSERT, to make sure it's inserted only once [duplicate]

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result:
email no longer exists publisher#example.com
This is the code I'm currently using:
if (count($_POST)) {
$email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($dbl, $query);
if (is_resource($result) && mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
} else {
echo "email no longer exists" . $email . "\n";
}
}
Is there a better way to check if a row exists in MySQL database (in my case, check if an email exists in MySQL)?
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query)) which should have simply read as if (!$query).
I apologize for overlooking that mistake.
Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_ with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
Prepared statements are best to be used to help protect against an SQL injection.
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
FYI: Forms default to a GET method if not explicity instructed.
Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.
POST arrays are case-sensitive.
Consult:
http://php.net/manual/en/tutorial.forms.php
Error checking references:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/pdo.error-handling.php
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).
You must use the same one from connecting to querying.
Consult the following about this:
Can I mix MySQL APIs in PHP?
If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:
MySql php: check if Row exists
The mysql_* functions are deprecated and will be removed from future PHP releases.
It's time to step into the 21st century.
You can also add a UNIQUE constraint to (a) row(s).
References:
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
How to check if a value already exists to avoid duplicates?
How add unique key to existing table (with non uniques rows)
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = #Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.
PDO
PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
For more examples see: How to check if email exists in the database?
MySQLi
As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]
For more examples see: How to check whether a value exists in a database using mysqli prepared statements
Minor remarks
If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record

Comparing if values exists in a MySQL table using PHP

Given the following code:
$checkuname = $connect->prepare('SELECT * FROM user WHERE username = ?');
$checkuname->bind_param("s", $uname);
$checkemail = $connect->prepare('SELECT * FROM user WHERE email = ?');
$checkemail->bind_param("s", $email);
$match = 0;
if ($checkuname->execute()) {
//if username matches//
$erroruname = "This username exists, please enter a new one";
$match = $match + 1;
}
if ($checkemail->execute()) {
//if email matches//
$erroremail = "This email has been used, please enter another one";
$match = $match + 1;
}
if ($match == 0) { //if no match, good to push data into database// }
No matter what happens, it always returns me saying that username exists (when it doesn't).
Is there any way to correct this?
Or if you think there would be an easier or clearer way to check if both username and email exists in a database, please do share too.
Just to mention too: Most tutorials I have found uses a single variable to check, but I need to check 2 variables
"#Fred-ii- I'll invite you to post an answer and I'll mark it as solved – Timothy Wong Glash"
As requested by the OP:
You can do this in one query.
$query = "SELECT `email`, `username` FROM `user` WHERE email=? AND username=?";
if ($stmt = $connect->prepare($query)){
$stmt->bind_param("ss", $email, $uname);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
// Number of binded results must match the number of columns in SELECT
$stmt->bind_result($email_check, $username_check);
$stmt->fetch();
// or num_rows >0
if ($stmt->num_rows == 1){
echo "That records already exists.";
exit;
}
}else{ echo "Error: " . mysqli_error($connect); }
}
Well, you are checking if the query executes, but you are not checking if the values returned are correct or not. What you need to do is verify how many rows are returned after executing the query, if a row is returned the user has been found. You can do that with num_rows.

Pulling data from Input Field From Mysql [duplicate]

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result:
email no longer exists publisher#example.com
This is the code I'm currently using:
if (count($_POST)) {
$email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($dbl, $query);
if (is_resource($result) && mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
} else {
echo "email no longer exists" . $email . "\n";
}
}
Is there a better way to check if a row exists in MySQL database (in my case, check if an email exists in MySQL)?
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query)) which should have simply read as if (!$query).
I apologize for overlooking that mistake.
Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_ with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
Prepared statements are best to be used to help protect against an SQL injection.
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
FYI: Forms default to a GET method if not explicity instructed.
Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.
POST arrays are case-sensitive.
Consult:
http://php.net/manual/en/tutorial.forms.php
Error checking references:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/pdo.error-handling.php
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).
You must use the same one from connecting to querying.
Consult the following about this:
Can I mix MySQL APIs in PHP?
If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:
MySql php: check if Row exists
The mysql_* functions are deprecated and will be removed from future PHP releases.
It's time to step into the 21st century.
You can also add a UNIQUE constraint to (a) row(s).
References:
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
How to check if a value already exists to avoid duplicates?
How add unique key to existing table (with non uniques rows)
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = #Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.
PDO
PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
For more examples see: How to check if email exists in the database?
MySQLi
As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]
For more examples see: How to check whether a value exists in a database using mysqli prepared statements
Minor remarks
If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record

Prevent duplicate data being entered into mysql database

I'm trying to make my email subscription service reject emails that already exist within my database so users don't subscribe the same email twice. this is what I have but its not working, any ideas?
<?php
if(!isset($_POST['submit']))
exit();
$vars = array('email');
$verified = TRUE;
foreach($vars as $v) {
if(!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if(!$verified) {
echo "<p style='color:white; margin-top:25px;'>*Email required*</p>";
exit();
}
$email = $_POST['email'];
if($_POST['submit']) echo "<p style='color:white; margin-top:25px;'>*Check your inbox* </p>";
// Create connection
$con=mysqli_connect("mysql.host","user","password","dbname");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO emails (email) VALUES ('$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
$query = mysql_query("SELECT * FROM emails WHERE email='$email'",($con));
if(mysql_num_rows($query) != 1)
{
echo "email already exists";
// redirect back to form and populate with
// data that has already been entered by the user
}
mysqli_close($con);
?>
The easiest way to let MySQL reject the duplicate e-mail address is to make the field unique (http://www.w3schools.com/sql/sql_unique.asp)
ALTER TABLE emails ADD UNIQUE (email)
However, MySQL will not return a warning
Use mysqli_num_rows($query) instead of mysql_num_rows($query)
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
$sql="INSERT INTO emails (email) VALUES ('".$_POST[email]."')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
Firstly, you're mixing MySQLi_ with MySQL_ so stick with MySQLi_ and modify the rest of your code accordingly.
This is the logic I use in my scripts, using ? instead of '$email'
$query = $con->query("SELECT * FROM emails WHERE email=?");
// $query = $con->query("SELECT email FROM emails WHERE email=?");
// you may need to use that one --^ if checking a particular column
$numrows=mysqli_num_rows($query);
if($numrows > 0){
die("Email already exists in the database, please try again.");
}
You can use this method, binding parameters. Assuming your column is named email
$query = "SELECT email FROM emails WHERE email=?";
if ($stmt = $con->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Beside mixing mysql and mysli
Use > not !=
if(mysqli_num_rows($query) > 1)
But this approach means you already have duplicates.
Maybe this will help after you put an unique index on the email column.
As noted in the other answers, you mixed mysqli and mysql functions.
for exemple in both these lines you use mysql instead of mysqli functions.
$query = mysql_query("SELECT * FROM emails WHERE email='$email'",($con));
if(mysql_num_rows($query) != 1)
I also think your code is easily SQL Injectable.
You are using $_POST["email"] in your insert query, without sanitizing it.
Have a look to at least the sql injection wikipedia page
My answer would be as follows,
First, create a UNIQUE KEY of the email column, and then:
INSERT INTO `table` VALUES (/*etc*/) ON DUPLICATE KEY UPDATE /*set a column equal to itself*/
This allows you to attempt inserting into the database, and you can choose whether or not the query throws an error. If you want it to throw an error, then simply do not use ON DUPLICATE KEY, and then catch the SQLException that is thrown from the query and tell the user that the email already exists.
Add a unique constraint to the email column.
Test for error returned on insert or update. I believe the code may be influenced if it is a primary key, foreign key, unique constraint on an index.
With PHP you can use
if( mysql_errno() == X) {
// Duplicate VALUE
} else {
// fail
}
You can test it yourself with a duplicate email or here are the mysql_errNo return values
For non PHP, to determine correct error code test it yourself with a duplicate email or look at the following.
MySQL Errors

Categories