I've checked many threads about my problem, but it still won't work.
When I enter username, which doesn't exist, it will throw the username has been created yet. But, when I enter an username already registered in my db, it still register.
Here is my php/html page for register :
$error = false;
if(isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
$query = mysqli_query($sql);
if(mysql_num_rows($query)){
$error = true;
$ckname_error = "Nom d'utilisateur déjà enregistré!";
} else { unset($ckname_error); }
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,mail,password,rank) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "', 'user' )")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
header("Location: login.php");
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
You're getting unreliable results because you're mixing mysqli_ with mysql_ functions.
1. Change:
$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
to:
$sql = "SELECT name FROM users WHERE name='$name'";
2. Change
$query = mysqli_query($sql);
to:
$query = mysqli_query($con,$sql);
3. Change
if(mysql_num_rows($query))
to:
if(mysqli_num_rows($query))
You missed $con, and use mysqli_num_rows not mysql_num_rows
$query = mysqli_query($con,$sql);
if(mysqli_num_rows($query)){
You're using mysqli_query($sql). You should have used 'mysqli_num_rows()' instead of mysql_num_rows().
PHP reference - mysqli_num_row
int mysql_num_rows ( resource $result ) expects resource type, whereas if you're using mysqli_query, you should have used int mysqli_num_rows ( mysqli_result $result ) - expects mysqli_results.
Let us know if it works.
Related
I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.
I have written this code , its working to add users but for duplicate user it again saved the value os same user name. i wanted to give popup message if username already taken. i m beginner please help.
<?php
ob_start();
include("db.php");
if(isset($_POST['send'])!="") {
$username = mysqli_real_escape_string($con, $_POST['username']);
$usermail = mysqli_real_escape_string($con, $_POST['usermail']);
$usermobile = mysqli_real_escape_string($con, $_POST['usermobile']);
$bool = true;
$con = mysqli_connect("localhost","root","","demo");
$result = mysqli_query("SELECT `username` FROM `sample` WHERE username = '$username'");
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
}
if ($bool) {
$inssql = "insert into sample set
username = '" . $username . "',
emailid = '" . $usermail . "',
mobileno = '" . $usermobile . "',
created = now()";
$update = mysqli_query($con, $inssql);
}
}
Make sure you finish the script or turn off your flag before making the insert:
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
die('username already taken');
//$bool = FALSE;
}
If you still having duplicate entries, debug what is the result of $username and compare it with the value in the database.
I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user
Problem:
Trying to run two MySQLi queries against the database but results always into a failure message.
Code (PHP):
// Checks whether submit button has been pressed
if (isset($_POST['submit']))
{
// Gets values from form fields
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
// Selects e-mail in database
$query = "SELECT * FROM userlogin WHERE email = '{$email}'";
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Checks whether e-mail exist
if (mysqli_num_rows($result) != 0)
{
// Register new user
$query = "INSERT INTO
userlogin
(username, password, email, regdate)
VALUES
('James','{$password}', '{$email}', NOW())
";
// Submit query to database
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Return success message
header('Location: index.php?notification=success');
}
else
{
// Return failure message
header('Location: index.php?notification=fail');
}
}
What am I missing? Any advice is appreciated.
Shouldn't this
mysqli_num_rows($result) != 0
be
mysqli_num_rows($result) == 0
One issue is
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
and should be
$email = mysqli_real_escape_string($link,stripslashes($_POST['email']));
$password = mysqli_real_escape_string($link,stripslashes($_POST['password']));
I am trying to return a username when a user forgets their username. I have it validating again their email address but for some reason it just keeps saying 'Error: cannot find username'. I am using the correct mysqli syntax I hope.
if (isset($_POST['user'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$username = "";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
$errmsg = 'Error: ' . $email . ' is not a valid email address';
} else {
$query = "SELECT email FROM admin WHERE email = '$email'";
$results = mysqli_query($con, $query);
$query2 = mysqli_fetch_array($results);
if ($query2 == 0) {
$errmsg = 'Error: ' . $email . ' is not found, please try again';
}
if (!errmsg) {
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con, $getuname)) {
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: ' . $row['username'] . '</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
}
I am a noob when it comes to this but am pretty sure this is correct. if not where did i go wrong?
These are some of the errors I noticed:
You're doing if (!errmsg) but there's no such constant and you want if (!$errmsg) instead.
As Marc B pointed out, you're doing $row = mysql_fetch_array($getuname); but you want $row = mysqli_fetch_array($getuname); instead.
Also, the specific problem you're describing is probably because of the $username declaration just before the mysqli_close statement. You're resetting the value of $username there and it'd always echo out the same message regardless of the result of your database query.
$username = "";
if(condition)
{
# code ...
}
else
{
# code ...
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
That's one of the many logical mistakes in your code. Structure the if-else blocks with proper indentation and you shouldn't have this issue.
I found some mistake in your code, you can see the mistake in Mark B and Amal Murali's answer. Let me make your else block simple and more clear. you can use only 1 query instead of 2 queries.
else {
$query = mysqli_query("SELECT * FROM admin WHERE email = '$email'");
$row = mysqli_fetch_array($query);
$numrows = mysqli_num_rows($query);
if (!$errmsg){
if($numrows == 0) {
$errmsg = 'Error: '.$email.' is not found, please try again';
// or here you can add message like Cannot find username
}
else
{
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
}
Your code is a disaster. You're using ereg, which has been deprecated since the stone age. You're mixing calls to the mysql (no i) and the mysqli (with i) libraries. They are NOT interchangeable and are NOT compatible with each other.
You need to switch over to the preg functions, and standardize on a SINGLE mysql library. Since mysql is deprecated as well, use mysqli ONLY.
$row = mysql_fetch_array($getuname);
^^^---note the LACK of an i
if (!errmsg){
^^^--note the lack of a $ sign, meaning this is undefined/undeclared constant.
Change this section of code:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con,$getuname))
{
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
to:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
$uresult = mysqli_query($con, $getuname);
if (!$uresult))
{
die('Error: ' . mysqli_error($con));
}
$row = mysqli_fetch_array($uresult);
if ($row) {
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
} else {
$username = '<div class="registererror">Error: cannot find username</div>';
}
}
Your mistakes:
You were calling mysql_fetch_array instead of mysqli_fetch_array.
You were passing the SQL string to mysql_fetch_array, not the result of mysqli_query.
You weren't checking whether a row was returned, you were just setting $username unconditionally -- first to the success message, then to the failure message.