Hi i want to make an insert in my mysql database but first I want to check if the email is not avaible in the table blacklist. If the mail is in the blacklist I want to ignore the insert.
$sqlinsertqueue = "
INSERT INTO queue Set
email = '$email'"
mysql_query($sqlinsertqueue,$db);
My blacklist has also the field email. My tablename from my blacklist is blacklist.
Since #EdGibbs deleted his answer before I got to say this, he was on the right track with an INSERT ... SELECT;
INSERT INTO queue (email)
SELECT 'dummy#example.com' FROM DUAL
WHERE 'dummy#example.com' NOT IN (SELECT email from Blacklist);
An SQLfiddle to test with.
You may want to use PDO or MySQLi instead of the deprecated mysql_* api, or at the very least do mysql_escape_string() on the email addresses before inserting them into the SQL query.
Something like this:
$email = mysql_real_escape_string($email);
//check blacklist
$sql = "
SELECT
COUNT(*)
FROM
blacklist
WHERE
email='$email'
";
$result = mysql_query($sql, $db);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$row = mysql_fetch_array($result, MYSQL_NUM);
if ($row[0] == 0)
{
//insert
$sqlinsertqueue = "
INSERT INTO queue Set
email = '$email'";
mysql_query($sqlinsertqueue,$db);
}
Don't use mysql_* functions - they are deprecated.
Related
I am trying to query two different tables just, to see if there is one match. I have done a lot of research on how to do this and all I keep seeing is using the join clause. But I am not looking for a match between two tables. I just need to query both tables and see if there is one row with a match.
This is the code I'm using.
$query = " SELECT id,account_type,email, password FROM client
WHERE email = ?
UNION
SELECT id,account_type,email, password FROM freelancers
WHERE email = ? ";
$email = $this->input->post("email");
$result = $this->db->query($query, [$email]);
// Just check if first there is an email that exists the database
if($result -> num_rows() == 1) {
//Do something
}
You could try using a subquery:
$query = "SELECT * FROM client WHERE email = (SELECT email FROM freelancers WHERE email = ?)";
$email = $this->input->post("email");
$result = $this->db->query($query, array($email));
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
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.
I want have an insert query, but before inserting I check whether the username and email are used by someone else. If used, I want to cancel insert query and echo a message to say whether username or email is in use.
Here my code:
$sql = "SELECT 1 FROM user WHERE username='".$_POST['username']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This username is already exists');
$sql = "SELECT 2 FROM user WHERE email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This email address is already exists');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
I want these three sql statements in one. It can be either using cases or something else that you suggest. So,
Is it possible to zip this code into one sql query?
As a result what I need is
sql = "sql_query"
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['result']==1)
die('This username is already exists');
else if($row['result']==2)
die('This email is already exists');
}
die('you have succesfully registered');
thanks for any advice.
While I suggest you follow #cularis' answer, you may be interested in the following alternative:
Give email and username the UNIQUE constraint, by creating a unique index for both of these.
run your INSERT query, and if this fails... (due to duplicate keys)
run the suggested combined SELECT, to determine which field existed (username or email)
You can combine the first two queries like this:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
Have look at mysql_real_escape string to sanatize your input.
Assuming you don't care about a more specific error case you could probably just do the following:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('The username or email address is already being used');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
This isn't the best of designs if you're looking for, as I said, specific error cases. So if you are okay with just telling the person there is an error that one or both are in use then that should work.
I am not sure as I am very rusty in PHP/MySQL but I assume that if such cases of both exist then multiple rows may be returned and I forget exactly how mysql_fetch_array works but I assume it's an array of all results valid for the query so you should be set. As long as the array exists, you know there was a hit in the db.
I have set my database fields "username" and "email" to unquie, when using the code below this only works if the "username" already exists, an error is then echoed. If they email exists the user gets a mysql duplicate error, when the same error as above should be shown.
<?php
require_once ( 'connection.php' );
$username=$_POST['username'];
$password=md5($_POST['password']);
$email=($_POST['email']);
$ip=$_SERVER['REMOTE_ADDR'];
session_start();
$query = "INSERT INTO users (username, password, email, rank, ip, active) VALUES ('$username','$password', '$email', '1', '$ip', '0')";
$sql = "SELECT username AND email FROM users WHERE username = '$username' AND email = '$email'" ;
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
if ( $count== 0 )
{
if (!mysql_query($query))
{
die('Error: ' . mysql_error());
}
echo "You are signed up, please follow the link on your email to active your account.";
}
else
{
echo "Username or Email already exists"."<br>Try Again</br>";
}
?
Thanks
Try switching
WHERE username = '$username' AND email = '$email'"
to
WHERE username = '$username' OR email = '$email'"
Edit: I'm trying to guess what you're trying to do here. From your description, it seems you want either the username or the email to be unique and you have two separate unique indexes on those columns. Your code checks for the combination of username and email to be unique.
Edit 2: Also, I think you might want to look into the concepts of SQL Injection and Concurrency.
Switch to an OR clause in your WHERE statement instead of AND.
Also, DO NOT use the values given in $_POST (or $_GET and $_REQUEST for that matter) without making sure they are safe. What would happen if I sent a username with SQL in it?
','','','','',''); DELETE FROM users;
Make sure you using add_slashes() or a similar process to clean the data before sending to the database.