php mysql check if username exists - php

i know maybe this post will be marked soon as duplicate, because there are a lot of questions answered but i dont know why it is not working for me (as always) here is this part of code:
$conn->set_charset("utf8");
$query = mysqli_query($conn, "SELECT * FROM User WHERE Username='".$username."'");
if(mysqli_num_rows($query) > 0){
echo "exists";
}else{
if (!mysqli_query($conn,$query))
{
echo "free";
}
}
}
Problem is : I'm always getting "Free"
thanks
-Nick

Try fetching the values and then using the php count() function on the query result. If count is greater than 0 echo taken else free

Why do you use a password in this query if you only want to check is a username is available? Did you also dumped the $numrows var to see which data it contains?
I would use something like
SELECT id FROM users WHERE username='username' LIMIT 1
You want to know if a username is available, so stop looking after you found 1 (LIMIT 1). If I ask you to find me 1 spoon,
As many others suggest, stop using the deprecated mysql_* functions. Try reading the tutorials on https://phpdelusions.net/pdo (much more can be found via Google)
When using PDO I think you can use the following code. Forgive me if it contains errors, it has been ages since I just PDO directly:
<?php
$checkUser = $pdoConnection->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
$checkUser->execute([$username]);
if ( $checkUser->rowCount() == 1 )
{
return 'Username exists';
}
# Username is available, so continue with the rest of your code
Small tip from me, based on experience, which has nothing to do with your question; never use capitals in your database. It could lead to unnecessary problems.

Your Username and Password are in quotes, so it is taking them literally.
Try this:
$query = mysql_query("SELECT * FROM User WHERE Username='" . $usernameG . "' and Password='" . $passwordG ."'");//quotes

Related

Check if username already exists in database

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']

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.

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.

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

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