Check if username already exists in database - php

I'd like to make an if statement that checks if the username, already exists in the MYSQL database. I tried some different stuff, but i cant make it work. Every time I test it in my browser I get a notice
Notice: Undefined index: username in etc.
I am confused if it has anything to do with the $result variable or the $check variable or neither.
Here is the HTML form and the PHP script.
https://gist.github.com/anonymous/9704354
Thank you and have a nice weekend!

There are a few things that are wrong in your code.
First, never place variables directly in SQL queries, thats how SQL injections happen. Start using PDO or another library for your MYSQL.
The reason you are getting an undefined notice is because of this line.
$result = mysql_query("SELECT * FROM users WHERE username = '$_POST[create_user]'");
It should be this without fixing the huge SQL Injection flaw
$result = mysql_query("SELECT * FROM users WHERE username = '{$_POST['create_user']}'");
Also you should add a "LIMIT 1" to the end of the select query to speed things up. No need looking for more than one user.
You can verify the user by just checking for row_count instead of checking the text values. Since MySQL is not case sensitive for some fields, username "AAAaaa" will be equal to "aaaAAA". If you check row count instead, you will be sure that no usernames are in the database of that text. Or if you want to check using PHP, make sure you pass the usernames through strtolower()
When you start using PDO, the following example will help you.
$dbh = new PDO() // Set the proper variables http://us2.php.net/pdo
if(empty($_POST['create_user'])) {
echo 'Username is Empty. Always check if POST and Get data is set';
die();
}
$query = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1;"
$data = array($_POST['create_user']);
$sth = $dbh->prepare($query);
if(!$sth->execute($data)) {
echo 'Handle SQL Error';
die();
}
if($sth->rowCount() == 0) {
echo 'Unused Username';
}else{
echo 'Used Username';
}

This is what i've found
the $_POST['username'] should be like $_POST['create_user']

Related

Adding a 'check username' to registration form PHP

Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.

SQL/PHP "WHERE" not returning correct value?

The code will display the returned values and and if it is greater than one it will return "Yes". But I am having trouble with the WHERE clause in $check. When I take it out the code works just fine but when I add it, the page returns incorrect values. Any ideas what's wrong?
<?php
$con = mysqli_connect("127.0.0.1","root","","lian");
$u= $_GET['username'];
$pw = $_GET['password'];
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
$login = mysqli_query($con,$check) or die(mysqli_error($con));
$num_rows = mysqli_num_rows($login);
echo "$num_rows \n";
if (mysqli_num_rows($login) == 1) {
$row = mysqli_fetch_assoc($login);
echo 'Yes';
exit;
}
else {
echo 'No';
exit;
}
Leaving aside the injection vulnerabilities, it may be because of special characters or whitespace. Try trim'ing your GET values.
$u = trim($_GET['username']);
$pwd = trim($_GET['password']);
Are you getting the number of results as 0? Also try echoing the statement in a development environment to check exactly what the statement is.
Try like this
$u= trim(mysqli_real_escape_string($_GET['username']));
$pw = trim(mysqli_real_escape_string($_GET['password']));
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
Also I hope you are ensuring unique combination of username and password.
Because suppose there are two entries in your users table
username="abc" password ="12345"
Then mysqli_num_rows() function will return two rows and the
if (mysqli_num_rows($login) == 1)
condition will return false meaning the user desn't exist.
The above comments are valid to improve the security of your code and protect vs sql injection.
Regarding your actual problem if the code executes correctly when you don't have the where clause in place but fails when you do there are a couple of possibilities:
The username or password are wrong - where wrong can mean they have extra whitespace, case insensitivities or that the column names are incorrect(case sensitive database?)
The string you are passing to the server is not displaying correctly.
Check both options by doing an echo of $u, $pw and $check right after you form your SQL string. If it's still not clear then copy whatever is echoed for $check and past it directly into the parser(management studio I guess?) and see what it returns.
Good Luck.

PHP If Statements With mySQL Results

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

how to get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

Simple PHP Login - num_rows

I am using mysql_num_rows to check if one row is returned for my user login and if count == 1 then log user in, I get an error though below my code is after that. Any suggestions?
Warning: mysql_num_rows(): supplied
argument is not a valid MySQL result
resource in
/home/web42001spring09/rcoughlin/public_html/process-login.php
on line 13
<?php
// include database info
include("config.php");
if(isset($_POST["submit"])){
// get data from form
$username = $_POST["user"];
$password = $_POST["pass"];
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
$result = mysql_query($query);
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}else{
echo "Must be submitted via form.";
}
Not sure why the code is drawing that issue? I have used this method before.
You're not quoting your strings in the query, so your SQL statement is invalid.
$query = "SELECT username,password,id FROM login WHERE username='" . mysql_escape_string($username) . "' AND password = '" . mysql_escape_string($password) . "' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
You need to add quotes AND use mysql_escape_string or mysql_real_escape_string to prevent SQL injection attacks.
Firstly, check for errors...
The "supplied argument is not a valid MySQL result resource" because there was an error in your SQL, but you haven't made life easy for yourself by ignoring the failed query. Use mysql_error to get the error message.
Secondly, properly escape strings in SQL...
Once you see the error, you'll see you missed some quotes in your query, but you must also escape the strings you put in a query, otherwise you're vulnerable to SQL injection attacks...
$query = "SELECT username,password,id FROM login ".
"WHERE username='".mysql_real_escape_string($username)."' ".
"AND password='".mysql_real_escape_string($password)."' LIMIT 1";
$result = mysql_query($query);
if ($result)
{
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}
else
{
echo "Error:".mysql_error()."<br>;
}
Always use mysql_real_escape_string when building a query, or use a wrapper class library which does it for you with parameterised queries, like PDO or ADODb
Finally, a word on those cookies...
Also, logging someone in by giving them a cookie with the username and password isn't a terribly good way to implement a login. Aside from transmitting the password in the clear with every request, it's highly vulnerable to a cookie theft attempt. Given your naive approach to SQL security, it's likely you'll also be leaving yourself vulnerable to XSS attacks making it easy for someone to collect those cookies :)
Looks like you might want to do 2 things:
Sanitise your input - passing user-submitted data straight into a database query is a recipe for disaster (see mysql_real_escape_string(string $unescaped_string)).
Put quotes around literals in database queries (i.e. username ='".$username."')
The error message you're getting is due to the fact that the MySQL result object ($result) is not valid. Try calling mysql_error() to see what error message MySQL returns.
Try:
$row = mysql_fetch_row($result);
if ($row) { // success
Assuming you'd probably want to fetch some columns along with the authentication check (e.g. real name, last login etc.)
Do never store user authentication data in a cookie!
Because both password and login are strings, you need to change the SQL:
$query="SELECT username,password,id FROM login WHERE username='".$username."' AND password='".$password."' LIMIT 1"
The query is invalid (the $result == false)
Line:
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
Should be replaced by:
$query = "SELECT username,password,id FROM login WHERE username='".mysql_escape_string($username)."' AND password='".mysql_escape_string$password)."' LIMIT 1";
The PHP mysql_query() function doesn't give errors by default.
Using a function that shows sql errors allow you to spot these errors easily.
function my_query($sql) {
$result = mysql_query($sql);
if ($result === false) {
trigger_error('['.mysql_errno().'] '.mysql_error(), E_USER_WARNING);
}
return $result;
}
Right now the username and password are injected directly in the sql string.
What you want is password = "secret", now the query contains password = secret
Mysql error "unknown column sercet"
PS:
Using a "LIMIT 1" here is a sign that there are several users (ids) using the same username password combination. (Not recommended)

Categories