Prevent duplicate data being entered into mysql database - php

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

Related

Inserting data into Mysql with PHP while loop

I'm trying to check an email against my database, and if it doesn't already exist, add it to the database.
$query = "SELECT * FROM users";
$inputQuery = "INSERT INTO users (`email`,
`password`) VALUES ('$emailInput',
'$passInput')";
$emailInput = ($_POST['email']);
$passInput = ($_POST['password']);
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
if ($row['email'] == $emailInput) {
echo "We already have that email!";
} else {
mysqli_query($link, $inputQuery);
echo "Hopefully that's been added to the database!";
}
}
};
It can detect an existing email, it's just the adding bit...
Currently this seems to add a new empty row for each existing row (doubling the size).
I'm trying to understand why it doesn't add the information, and how to escape the loop somehow.
Also for good measure, everyone seems to reuse $query, but this seems odd to me. Is it good practice to individually name queries as I have here?
Please let me know if there's anything else I should add.
I am not going to talk about the standards but straight, simple answer to your question.
Approach - 1:
INSERT INTO users (`email`,`password`) SELECT '$emailInput', '$passInput' from DUAL WHERE NOT EXISTS (select * from users where `email` = '$emailInput');
Approach - 2:
- Create a unique key on email column
- use INSERT IGNORE option.
user3783243 comments are worth noting
Try this :
$emailInput = mysqli_real_escape_string($link, $_POST['email']);
$passInput = mysqli_real_escape_string($link, $_POST['password']);
$qry3=mysqli_query($link,"select * from users where `email`='".$emailInput."'");
$num=mysqli_num_rows($qry3);
if($num==1) {
echo "Email-Id already exists";
} else {
$inputQuery = mysqli_query($link,"INSERT INTO users (`email`, `password`) VALUES ('".$emailInput."', '".$passInput."')");
if ($inputQuery) {
echo "Hopefully that's been added to the database!";
}
}
Your code seems to be a bit over-engineered because why not to pass you $_POST['email'] to select query where clause
"SELECT * FROM users where email = $emailInput" and then check if it is there already.
Also, keep in mind that this is an example only, and you should always check and sanitize user input.
From another hand you can do it with MySQL only using INSERT ... ON DUPLICATE KEY UPDATE Syntax. https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
That requires to add unique key for email column.

How to know if an email is already with your site using PHP [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

Check and Return Value in Mysqli_query

I am Android developer and trying to make one API for register user using PHP and Mysqli. I have made API like below
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
basically I am passing email as parameter like example.com/login?=abc#gmail.com
and I want check that email is already in database table or not. if email exist in database I want return user_id in response and if email is not in database than I want add that email in database and want return user_id. I have made API is working fine as I require but I do not know how to return user_id located with that email. Let me know if someone can give me idea to solve my puzzle. Thanks
The below code will create an array with message and user_id.
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
Prepared statements help you secure your SQL statements from SQL Injection attacks.
First of all, you should use PreparedStatement to avoid sql injection.
Then, second you can use PDO::lastInsertId()

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

Checking if row exists under criteria (PDO, prepare???)

The code below indicates my attempts to try and find out whether a row exists with the criteria gave in the code. It defaults to the else statement, correctly, but doesn't work with the 'if' statement if the if statement appears to be true (there are no emails down as ashfjks#sdhja.com), and instead the code proceeds. The latter part of this code is mostly to expand on the situation. the row can only exist or not exist so I don't understand why it's not strictly doing one or the other. I am converting into PDO for site secuirty, thats why not all is in PDO, yet. I am sorry if this question is too localised?
$stmt = $pdo->prepare("SELECT * FROM table WHERE email = ?");
$stmt->execute(array("$email"));
$row3 = $stmt->fetch(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
if ( ! $row3) {
// Row3 doesn't exist -- this means no one in the database has this email, allow the person to join
$query = "INSERT INTO table (username, email, password, join_date) VALUES ('$username', '$email', SHA('$password1'), NOW())";
mysqli_query($dbc, $query);
$query = "SELECT * FROM table WHERE username = '$username'";
$data2 = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data2)) {
$recipent = '' . $row['user_id'] . '';
$query = "INSERT INTO messages (recipent, MsgTit, MsgR, MsgA, sender, time, readb, reada, MsgCon) VALUES ('$recipent', '$MsgTit', '$MsgR', '$MsgA', '$sender', NOW(), '$readb', '$reada', '$MsgCon')";
mysqli_query($dbc, $query);
// Aftermath.
echo '<p>Your new account has been successfully created. You\'re now ready to log in. After this you should implement basic character-details on your users profile to begin the game.</p>';
mysqli_close($dbc);
exit();
} }
else {
// An account already exists for this email, so display an error message
echo '<p class="error">An account already exists for this e-mail.</p>';
$email = "";
}
}
Your if statement will never be executed. You need to check the number of rows returned. This is what you want:
Note: I originally used $stmt->rowCount(), but the OP said that didn't work for him. But I'm pretty sure the cause of that error was coming from somewhere else.
if (!($stmt = $pdo->prepare("SELECT * FROM table WHERE email = ?"))) {
//error
}
if (!$stmt->execute(array("$email"))) {
//error
}
//The $row3 var you had was useless. Deleted that.
$count = 0;
while ($row = $stmt->fetch()) {
$count++;
}
//The query returned 0 rows, so you know the email doesn't exist in the DB
if ($count== 0) {
$query = "INSERT INTO table (username, email, password, join_date) VALUES ('$username', '$email', SHA('$password1'), NOW())";
if (!mysqli_query($dbc, $query)) {
//error
}
$query = "SELECT * FROM table WHERE username = '$username'";
if (!($data2 = mysqli_query($dbc, $query))) {
//error
}
while ($row = mysqli_fetch_array($data2)) {
$recipent = '' . $row['user_id'] . '';
$query = "INSERT INTO messages (recipent, MsgTit, MsgR, MsgA, sender, time, readb, reada, MsgCon) VALUES ('$recipent', '$MsgTit', '$MsgR', '$MsgA', '$sender', NOW(), '$readb', '$reada', '$MsgCon')";
if (!mysqli_query($dbc, $query)) {
//error
}
// Aftermath.
echo '<p>Your new account has been successfully created. You\'re now ready to log in. After this you should implement basic character-details on your users profile to begin the game.</p>';
mysqli_close($dbc);
exit();
}
}
//The query did not return 0 rows, so it does exist in the DB
else {
// An account already exists for this email, so display an error message
echo '<p class="error">An account already exists for this e-mail.</p>';
$email = "";
}
And you should totally convert the rest of those queries to use PDO.
+1 to answer from #Geoff_Montee, but here are a few more tips:
Make sure you check for errors after every prepare() or execute(). Report the error (but don't expose your SQL to the user), and fail gracefully.
Note that even though you checked for existence of a row matching $email, such a row could be created in the brief moment of time since your check and before you INSERT. This is a race condition. Even if you SELECT for a row matching $email, you should also use a UNIQUE constraint in the database, and catch errors when you execute the INSERT in case the UNIQUE constraint blocks the insert due to conflict.
SELECT email instead of SELECT *. If you have an index on email, then the query runs more efficiently because it can just check the index for the given value, instead of having to read all the columns of the table when you don't need them. This optimization is called an index-only query.
Likewise use SELECT user_id instead of SELECT *. Use SELECT * only when you really need to fetch all the columns.
Bcrypt is more secure than SHA for hashing passwords.

Categories