Check if username exists in mysql table via php? [duplicate] - php

This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>

$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code

include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.

Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie

Related

How to check if a User already exists in a MySQL database and if the password matches stored hashed password [duplicate]

This question already has answers here:
Check if value exists before inserting into MySQL DB in a PHP script
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 9 years ago.
I am trying to figure out how to have my register php code check whether or not the registee's username is already taken, and if it is, don't register it, tell the user that it's taken.
Here's my entire register processing file.
<?php
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$hpassword = hash( 'sha512', $_POST['password'] );
$eusername = mysqli_real_escape_string( $con, $_POST['username'] );
$eemail = mysqli_real_escape_string( $con, $_POST['email'] );
$fusername = str_replace(' ', '', $eusername);
$sql="INSERT INTO users (username, password, email)
VALUES
('$fusername','$hpassword','$eemail')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
$sql=mysql_query("SELECT FROM users (username, password, email) WHERE username=$fusername");
if(mysql_num_rows($sql)>=1)
{
echo"name already exists";
}
else
{
//insert query goes here
}
you can check from database whether user exists and then paste the code
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'Please Enter a name ';
} else {
$username = $_POST['username'];
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL)) {
//for email validation (refer: http://us.php.net/manual/en/function.filter-var.php)
$email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
}
if (empty($error))
{ // If everything's OK...
$query = "SELECT * FROM members WHERE username ='$username'";
$result = mysqli_query($dbc, $query); // here $dbc is your mysqli $link
if (!$result) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result) == 0) { // IF no previous user is using this username.
$query = "INSERT INTO `members` ( `username`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send an email
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The username is not available.
echo '<div class="errormsgbox" >That username has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them.... e.g....
echo '<div class="errormsgbox"> <ul>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ul></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
Either you can use Dave's way and check' the error code, or you can precheck whether the user exists
$sql="SELECT FROM users (username, password, email) WHERE username=$fusername"
Now check the results of this. If a row is fetched, then the user exists. Indicate this to the user. If not, the sun is shining on the user. Give him a cookie

how to get get sign up message on my webbrowser

0
I'm setting up the wholly organized sign up form, I'm trying to sent into information into my MySQL database server. My code not work and can't figuring out pops up message You have been signed up!
I've tried several options but none of them work on a server,
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
if (mysqli_connect_error()) {
die("There was an error connecting to the database");
}
if ($_POST['email'] == '') {
echo "<p>Email address is required.</p>";
} else if ($_POST['password'] == '') {
echo "<p>Password is required.</p>";
} else {
$query = "SELECT `id` FROM `users` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo "<p>That email address has already been taken.</p>";
} else {
$query = "INSERT INTO `users` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
}
}
}
?>
When I signed up form only pops up "There was a problem signing you up - please try again later" I want to expect to "you have been signed up" from the result .
here is the problem

Error in SQL syntax: Update query error

I working in my login form and 1 requirement is to have a change password. For some reason I'm always getting this error-> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' SET 'password'=SHA1('123') WHERE 'email'='mac.pader#yahoo.com'' at line 1.
<?php
$page_title = 'Change Your Password';
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('userdb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
//Start the Session
session_start();
if (isset($_POST['email']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$email = $_POST['email'];
$password = $_POST['password'];
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = $_POST['pass1'];
}
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT userid FROM `users` WHERE email='$email' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['email'] = $email;
$_SESSION['np'] = $np;
//$row = mysqli_fetch_array($result, MYSQLI_NUM);
// Make the UPDATE query:
$query = "UPDATE 'users' SET 'password'=SHA1('$np') WHERE 'email'='$email'";
$result = mysql_query($query) or die(mysql_error());
echo"$np and $email";
$count = mysql_num_rows($result);
if ($count == 1){
}else{
// Public message:
echo '<h1>System Error</h1>
<p class="error">Your password could not be changed due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
// Include the footer and quit the script (to not show the form).
//include ('includes/footer.html');
exit();
} else { // Invalid email address/password combination.
echo '<h1>Error!</h1>
<p class="error">The email address and password do not match those on file.</p>';
echo"$num";
}
}
//3.1.4 if the user is logged in Greets the user with message
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo'<h1>Thank you!</h1>
<p>Your password has been updated. You can now Log-In!</p><p><br /></p>';
}else{
echo'try again';
}
mysql_close($select_db);
exit();
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your new password did not match the confirmed password.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your new password.';
}
?>
You have to use backticks arround table and field names not single quotes:
UPDATE `users` SET `Password`=SHA1('$np') WHERE `email`='$email'
Also you should not use mysql_* functions because this API is depricated.

getting my sql insert query to work within a function

I have a form that passes input data to a processing page. This processing form then checks whether the email and user name already exists in the database. If they do, an error is reported, the function I am having difficulty with is, if the error reports nothing then go and execute the sql insert query otherwise echo the error. I can get most of it to work except the insert data to database. Can anyone help me see the error in my code please ?
Processing page :
<?php
session_start();
list($username,$email,$clubname, $hash) = $_SESSION['data'];
unset($_SESSION['data']);
include_once 'db_connect.php';
$usernameErr = $emailErr = "";
$password = $hash;
$databaseErr = 'cannot connect to database';
$query1 = mysqli_query($mysqli, "SELECT * FROM members WHERE email='".$email."'");
if(mysqli_num_rows($query1) > 0){
// echo 'email already exists';
$usernameErr = "username already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query1))
{
die('Error: ' . mysqli_error($mysqli));
}
}
$query2 = mysqli_query($mysqli, "SELECT * FROM members WHERE username='".$username."'");
if(mysqli_num_rows($query2) > 0){
// echo 'username already exists';
$emailErr = "email already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query2))
{
die('Error: ' . mysqli_error($mysqli));
}
}
if ($usernameErr == "" && $emailErr == "" ) {
$sql = mysqli_query($mysqli, "INSERT INTO members (username, email, password, clubname) VALUES ('$username', '$email', '$password', '$clubname')");
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
}
else {
echo $usernameErr.'<br/><br/>';
echo $emailErr.'<br/><br/>';
}
I came up with this, a simple skeleton, just edit to suit you. Don't forget to hash the password parameter.
function emailEmailExists($emall) {
if(mysqli_num_rows($email) >= 1) {
return 1;
} else {
return 0;
}
}
function usernameExists($username) {
if(mysqli_num_rows($username) >= 1) {
return 1;
} else {
return 0;
}
}
function insertUser($username, $password, $email, $otherField, $otherField, ) {
if(checkEmailExists($email) == 1) {
echo 'Email in use!';
} else if(usernameExists($username) == 1){
echo 'Username in use!';
} else {
$insertUser = mysqli_query($yourQuery);
if($insertUser) {
echo 'User created!';
} else {
// Give error.
}
}
}
Edit
How do you create you DB connection, remove your credentials and please show.

My MySQL query and while loop and SESSIONS aren't working PHP

In my signup up form I automatically log the user in after they submit all their data. After they submit their data to the database, I run a query to grab that data from the database and store it in session variables. The problem is that The while loop only stores the first variable which is the user ID and doesn't store the rest. What I am Doing wrong?
if ($signup) {
//user clicked the register button
if (isset($username, $em, $pass, $pass2, $fn, $ln, $sex, $bd_day, $bd_month, $bd_year)) {
//if all of these have a value
if ($pass == $pass2) {
//if the passwords match
$sql = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE username = '$username'"));
//check if username is already taken
if ($sql < 1) {
//if the username hasn't been taken
$sql2 = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE email = '$em'"));
//check if the email is taken
if ($sql2 < 1) {
//the email hasn't been taken
if (strlen($pass) > 5) {
//password is more than 5 characters
$pass = md5($pass);
//md5 is not secure!!! use something else later
if (strlen($username) > 4) {
//username is bigger than 4 characters
$query = mysqli_query($con, "INSERT INTO users (username, email, first_name, last_name, sex, bd_month, bd_year, bd_day, password, profile_pic, signup_date, activated, cover_photo) VALUES ('$username','$em','$fn', '$ln', '$sex', '$bd_month', '$bd_year', '$bd_day', '$pass', 'profilepic/default.png','$date)','0', 'coverphoto/defaultcover.jpg')") or die(mysqli_error($con));
//insert into db
$sql3 = mysqli_query($con, "SELECT * FROM users WHERE username = '$username' AND email = '$em'") or die(mysqli_error($con));
//select values from db for login
$num = mysqli_num_rows($sql3);
//check how many hits the query gets it should be 1
if ($sql3 == true && $num > 0) {
//check if query was a success and that there is a user with those credentials
while ($row = mysqli_fetch_assoc($sql3))
//log user in
$_SESSION['id'] = $row['id'];
echo $_SESSION['id'] . '<br>';
$_SESSION['un'] = $row['username'];
echo $_SESSION['un']. '<br>';
$_SESSION['fn'] = $row['first_name'];
echo $_SESSION['fn'] . '<br>';
$_SESSION['ln'] = $row['last_name'];
echo $_SESSION['ln'] . '<br>';
$_SESSION['em'] = $row['email'];
echo $_SESSION['em'] . '<br>';
$_SESSION['pp'] = $row['profile_pic'];
echo $_SESSION['pp'] . '<br>';
$_SESSION['signup_date'] = $row['signup_date'];
$_SESSION['active'] = $row['activated'];
setcookie('un', $username, time()+3600*60*24*7*4);
echo "You have been logged in.";
exit();
} else {
echo "An unknown error occurred";
exit();
}
} else {
//username is less than 4 characters
echo "Your username must be larger than 4 characters!";
exit();
}
} else {
//password is less than 5 characters
echo "You password must be more than 5 characters long<br />";
exit();
}
} else {
//email is already taken
echo "That email has already been taken!";
exit();
}
} else {
//username is already taken
echo "That username is already taken!";
exit();
}
} else {
//the passwords don't match
echo "You passwords don't match";
exit();
}
} else {
//user didn't submit the form
echo "Please fill in all the fields";
exit();
}
} else {
//user didn't click the register button
}
In the end it does echo You have been logged in. Also, I echoed out the values in the session variables for testing but all the return are the <br> not the actual values except for the user ID at the beginning. I don't get any errors either.
Please help me.
while ($row = mysqli_fetch_assoc($sql3))
You forgot to add { and it seems that also } at the end of the loop.
So only the first command takes place in the loop and executed.
Another thing, the "else" after the loop - to which condition is it relate?
Usually I think indents are good, but you took it too far.
Maybe, instead of nesting too many conditions and loops, find another approach.

Categories