This question already has answers here:
Check if a row exists using old mysql_* API
(6 answers)
Closed 7 years ago.
I have a simple PHP file in which I check if the users email exists in my database using the following code:
$query = "SELECT * FROM userData WHERE email = '$email'";
$result = mysql_query($query);
Which works perfectly fine when the user enters an email address that is in the database, however, when I want to determine if this $query is null or empty - I'm not sure which one though.
When I enter an email that isn't in the database and add the following code in below:
if(is_null($result)){
echo 'email not in database';
}
the code in the {} isn't executed.
I was just wondering if you could help me out.
Hi again,
Sorry for the duplicating another post. I corrected it by using:
if(mysqli_num_rows($result) > 0)
{
// a row with email exists
}
else
{
// no row with particular email exists
}
You can directly check whether your query executed or not by
if($result > 0){
// perform some action
}
You should use mysqli_ instead of mysql_ as it is deprecated and will be removed in future.
what you need is mysqli_num_rows() to see if atleast 1 row was in the table or not
for reference - num_rows
if(mysqli_num_rows($result) > 0)
{
// a row with email exists
}
else
{
// no row with particular email exists
}
Try this
$row = mysql_fetch_rows($result);
if(!$row){
echo 'email not in database';
}
OR
$num = mysql_num_rows($result);
if($num == 0){
echo 'email not in database';
}
You can try this too !
if(empty($result)){
echo 'email not in database';
}
empty() will check if $result is null, or its value is 0, or if $result doesn't exists.
See here : http://php.net/manual/fr/function.empty.php
Related
I'm currently coding a registration script in PHP and my problem is that the data is still inserted into the database even though it already exists. It's probably some silly mistake or I need some else{} statement or I don't really know. The thing is that even though the email already exists in the database it stills enters it.
It does display the error just fine.
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
$email = filter_var($email,FILTER_VALIDATE_EMAIL);
$email_check = mysqli_query($con, "SELECT email FROM database WHERE email='$email'");
$num_rows = mysqli_num_rows($email_check);
if($num_rows>0){
echo "The email is already in use.<br>";
}
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
?>
If the email is already in use it displays the echo "The email is already in use." just fine, yet it still inserts it. What am I missing? I already tried using 'else' variable yet nothing helped.
Your if only echo something, then you do the INSERT no matter what. Some solution :
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
$email = filter_var($email,FILTER_VALIDATE_EMAIL);
$email_check = mysqli_query($con, "SELECT email FROM database WHERE email='$email'");
$num_rows = mysqli_num_rows($email_check);
if($num_rows>0){
echo "The email is already in use.<br>";
}
// ADD A ELSE SO YOU INSERT IF YOU HAVE NOTHING
else {
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
}
Now you can prevent it from your database too :
Add a UNIQUE INDEX on the column email from your table database
Use INSERT IGNORE now, so it will insert if the email is not used and ignore if email is already used
And last, use prepare statement and bind param to avoind SQL injection !
Hope it helps
Your if is fine, but you then proceed to always do the insert. This is because you have put it outside the if.
what you should do is :
if(!$num_rows <= 0){
<insert statement>;
}
else {
echo "The email is already in use.<br>";
}
write this statement inside else block
else
{
$query = mysqli_query($con,"INSERT INTO database VALUES (NULL,'$username','$name','$email','$pwh','$date')");
}
I'm new to PHP and am practicing by programming a very basic signup form, which dumps the info into a MySQL database. However, I'm having a problem where, even if the name is taken, my program still adds the account to the SQL table.
This is my code to check if the name exists:
$sql = "SELECT * FROM accounts WHERE name = '$name'";
$result = $conn->query($sql);
if (mysql_fetch_array($result) === true) {
die("Error: Username has been taken");
} else {
//register account
}
Every time I run this, no matter what the name is, the program runs the block of code inside the else statement. I can provide more info if needed.
if you are using mysqli then use.
if ($result->num_rows > 0) {
die("Error: Username has been taken");
}
else {
// register here;
}
P.S do not use mysql read here.
You can alter the table and add make the field unique.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create an activation page that will GET the API & ACT codes from the url.
Then I am trying to query the DB on those codes to check if they're valid.
If they are not valid, I would like to echo an error stating echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
If it is valid, then I would like to update with the 2nd SQL Query - "UPDATE users SET status='1', date_activated='$Activation_Date', Activation='' WHERE Activation='$Activation' AND API='$API' AND status='0'"
If there is NO API&ACT code in the URL, I would like to echo "CONTENT"
<?
require 'admin/config.php';
require 'Connection.php';
error_reporting(E_ALL);
$API = $_REQUEST['api'];
$Activation = $_REQUEST['act'];
$sql= mysql_query("SELECT * WHERE Activation='$Activation'");
if ($sql = 0) { echo"ERROR";}
else {
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if($sql == 0){
echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
} elseif ($sql > 0) {
echo "content";
}
}
?>
What you need to check for, is if a row exists.
To check if it exists and base yourself on the following model:
$sql = mysql_query("SELECT * WHERE Activation='$Activation'");
if(mysql_num_rows($sql) > 0){
//do something here or show error because relation already exists
}
else{
//relation already do not exists. so you can insert the record here
}
Then, to check if your UPDATE was truly successful, use mysql_affected_rows():
Sidenote: This function may require that you pass a db connection variable to it.
$sql = mysql_query("UPDATE users .... ");
if(mysql_affected_rows() > 0){
// do something
}
else {
// do something else
}
Check for errors against your PHP and MySQL:
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If you get errors about deprecation notices, then you will need to switch over to either mysqli_ or PDO.
You can consult one of my answers here https://stackoverflow.com/a/22253579/1415724 to check if a row exists.
It uses a few methods, including a prepared statement which is something you should be using because you are open to an SQL injection.
Sidenote: The connection API that you are using is unknown. Make sure that you are using the same one as your query being mysql_. If it's mysqli_ or PDO, those different APIs do not intermix. You must use the same one from connecting to querying.
Also, just a quick note about if ($sql = 0). The single equal sign "assigns" instead of "comparing" such as == or ===.
You stated in comments:
"IF the Activation code is active (the md5 has will be there)"
I hope you're not using that for password storage. If so, don't. That function is no longer safe to use to store passwords with.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Seeing <? make sure that short tags are enabled. If not, change that to <?php.
HTML stickler.
<font color=red> the <font> tag is deprecated/obsole and isn't supported by HTML5.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font
It's best to use inline CSS if you are sending anything via Email.
I.e.: <p style="color:red;">Hello world</p>
Here are a few references:
http://www.tizag.com/cssT/inline.php
Inline <style> tags vs. inline css properties
http://webdesign.about.com/od/beginningcss/qt/tipcssinlinesty.htm
Remarks
Checking mandatory parameters:You can test if parameters are set like this:
isset(variable_name).
In the SELECT query there is missing the FROM clause which states the table to select from.I assume it is "user" like in the UPDATE query.
After a SELECT query, the cursor should be freed again, when it is no longer in use: mysql_free_result($sql);
(Error) Tests
The result of a query is ===false if the query could not be executed corectly.
After having SELECTed records, the function mysql_num_rows() shows the number or records retrieved.
After having UPDATed a table, the function mysql_affected_rows() gives the number of affected records.
Code snippet
// Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
$which = ($API === false ) ? '"api"' : '';
$which .= ($Activation === false) ? ((empty($which) ? '' : ', ') . '"act"') : '';
echo "ERROR: Parameter(s) missing: $which";
return;
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows();
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "ERROR: No activation record found";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "content";
}
}
}
Here is what I ended up with.
This is a Tweak from #hherger's answer....
// Report all errors
error_reporting(E_ALL);
// Get parameters and check if mandatory parameters are set // Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows($sql);
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "REDIRECT USER TO HOME PAGE";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE pinAPP_Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "ECHO SUCCESS DISPLAY!";
}
}
}
This is my first topic so far in this great webpage
The problem is this:
I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.
It was working properly before I made some changes (Checking if the username exists)
Here's the code:
if (isset($_POST['login']))
{
$hashedpass = hash('whirlpool', $password);
$query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
else
{
$name=mysql_result($result,$i,"UserName");
$money=mysql_result($result,$i,"Money");
$score=mysql_result($result,$i,"Score");
$wantedlevel=mysql_result($result,$i,"WantedLevel");
$adminlevel=mysql_result($result,$i,"AdminLevel");
echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";
}
}
else if (isset($_POST['register']))
{
header("Location: register.html");
}
else
{
header("Location: index.html");
}
if($num != 0)
change to:
if($num == 0)
This simply won't work here nor does it make much logical sense:
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:
if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
echo "Account doesn't exist!";
}
Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.
Finally check your MYSQL is not causing an error by adding a check at the end with :
$result = mysql_query($query) or die(mysql_error());
Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here:
Why shouldn't I use mysql_* functions in PHP?
<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!
Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}
$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.
I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this