I am working on a code for my music site. This is part of the registration phase. I want the code to check the database for any existing email addresses, if found, print " email ("email address") already exists, but if not found, then insert the information into the database. The code seems to run if an email address similar to the one submitted from the html form is found, but if there is no email found, the system stops and does nothing after that. Can someone help me figure out where i went wrong.
if ($_POST['submit2']){
$fname = $_POST['Fname'];
$sname = $_POST['Sname'];
$email = $_POST['Emailaddress'];
$pass = $_POST['newpassword'];
$sql= "select * from cust_information where email = '$email';";
$results = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row = mysqli_fetch_array($results) or die(mysqli_error($conn));
if (count($row) < 0)
{
$sql2 = "insert into cust_information (firstName, lastName, email, password) values(`$fname`, `$sname`, `$email`, `$pass`)";
$results2 = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (!$results2){
echo "successfully uploaded cust";
}
}else{
echo "email <strong>".$row["email"]. " </strong> already Exist";
}
}
You are checking whether the number of results returned is less than 0. The length of an array (and the number of results found) cannot ever be less than 0. The manual shows that mysqli_fetch_array returns null if no results are found, thus you want to check for $row === null.
However, I will take this opportunity to point out that concatenating variables into a SQL query string leaves you wide open to a serious security concern called SQL Injection. As the code is currently set up, users of the form will be able to run any query they like on your database which is absolutely not what you want. I recommend reading up on prepared statements to mitigate this problem.
Related
I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];
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 am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.
This register form was made by me, but it doesn't do what I want it to do.
I want it to connect to a mysql database and store the information that was given by the form. I want it to hash the $password in md5 and store it in the "gebruikers" table. Please don't reply with "Damn, you have no idea what you are doing" or something like that. I am learning PHP by looking to examples and following tutorials. Please keep in mind that the mysql insert code is not filled in right, because I got stuck a few lines above.
So, my question is: I want to check if the mysql table already contains $email. If it IS already in the mysql table, I want to display an error message that I can place somewhere else in my PHP page. If the email adress given is unique, than the $password should hash into md5 and store into the mysql database, just like the other form entries.
How do I do that?
<?php
// Fetching all the form details
$email = $_POST["email"];
$password = $_POST["password"];
$voornaam = $_POST["voornaam"];
$tussenvoegsel = $_POST["tussenvoegsel"];
$achternaam = $_POST["achternaam"];
$dag = $_POST["dag"];
$maand = $_POST["maand"];
$jaar = $_POST["voornaam"];
$straat = $_POST["straat"];
$postcode = $_POST["postcode"];
$woonplaats = $_POST["woonplaats"];
$cniveau = $_POST["cniveau"];
$oniveau = $_POST["oniveau"];
$voornaam = $_POST["voornaam"];
$aboutme = $_POST["aboutme"];
//Here's where I don't know how to continue
$check = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email'");
if($check === FALSE) {
//there is a user already registered
echo("$email is al in gebruik. <a href='login.php'>Inloggen</a>?");
} else {
//There isn't a username
//mysql_query("INSERT INTO `user` (`id` ,`username` ,`password`) VALUES (NULL , '{$_POST['email']}', MD5( '{$_POST['password']}' ))");
echo("You have been registered!");
}
P.S.: I'm not a native English speaker, so please ignore my grammar mistakes/typos.
First of all, you made a major mistake: There is a SQL-Injection security hole.
Please read this: http://php.net/manual/en/security.database.sql-injection.php
Second, you should use mysqli instead of mysql, because mysql is deprecated.
Your error is that SQL does only return false if the query is invalid, not if there are no results. So the correct way of checking if there are results is to use http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email' LIMIT 1");
if(mysql_fetch_array($result) !== false)
{
...
} else {
....
}
You should also read up on preventing SQL injection.
Maybe you've forgot to set the mysql_connect statement.
But I strongly recommend you stick from now on, with the mysqli_ functionality, since, as Aragon0 said, mysql is deprecated in PHP's newest versions.
Besides, mysqli statements are simpler than the mysql ones, for example you use one statement (mysqli_connect) to connect to your host and select your database at the same time, instead of using separated statements (both mysql_connect and mysql_select_db).
Oh, and no additional service package is required to use it. :)
Hello I facing a strange problem; I am using this code to check the login data with my db
include("includes/config.php");
include("includes/database.php");
$name = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM info_user WHERE user_name = '$name' AND password = '$pass'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['user_name']. " - ". $row['password'];
if (mysql_num_rows($sql)) {
echo "success";
}
else
{
echo "failed";
}
here, when i succeed it shows success but any blank input or wrong input is not showing the failed message why? and how can I solve it? is there any better way to check the login? please help
Thanks in advance
First off:
$row = mysql_fetch_array($result) or die(mysql_error());
If you pass along a wrong username or password, mysql_fetch_array() will return FALSE, because there is no rows to take from. This results in your or die(mysql_error()) part being executed, which means your script dies and outputs nothing since mysql didn't fail - which again means that mysql_error() has nothing to return to you.
Secondly, you are using mysql_num_rows() on the $sql string, not on the $result variable which actually contains a mysql resource that you should be using.
You should also check the mysql_num_rows() before using mysql_fetch_array() so that you don't try to pull out some data you don't have available.
Lastly, your solution is full of security flaws. You are passing along raw post data to your mysql database which makes you vulnerable to sql injection and you are storing your passwords as plain text values in your database (not plain text files, just plain text values).
You should google sql injection and password hashing to improve your security.
Try this:
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
echo "success";
} else {
echo "failed";
}