I want to search my database to see if a user that is registering is using a username that is currently in my database. I have registered the same name about 5 times so it SHOULD return false but it returns true.
<?php
function registerUser($userName, $userPassword) {
$db = new dbinterface();
$db->connect();
// check for duplicate data
$checkduplicates = "SELECT * FROM usersexample WHERE $userName = :userName";
$myresult = mysql_query($checkduplicates);
if(mysql_num_rows($myresult) > 0){
echo $myresult;
return false;
}
?>
My table name is usersexample and the field i am searching is userName.
ANY and ALL help is appreciated!
Using mysql_num_rows in examples i get this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource.
Use mysql_num_rows() to check the number of rows returned.
Sample:
$myresult = mysql_query($checkduplicates);
$rowcount = mysql_num_rows($myresult);
if($rowcount > 0)
{
// Account name already in use
}
You should try this...
if(mysql_num_rows($myresult) > 0) {
echo $myresult;
return false;
}
It will return false if there is a duplicate username.
$getduplicates = mysql_query("SELECT * FROM table WHERE username = $username");
$duplicates = mysql_num_rows($getduplicates);
if($duplicates){
echo "Uh oh someone already has that username";
}
else {
echo "Everything is allllllll good";
}
Please use prepared statements to avoid sql injection.
As you are using :userName in your SQL it seems you are trying to do this (is your
database class based on PDO by any chance?). The :userName part will be replaced
by your variable $userName when you do the bindValue.
Use count() in the database to count the number of records found,
the database knows best ;-)
$query = $db->prepare("SELECT count(*) AS no_found FROM usersexample WHERE userName = :userName");
$query->bindValue(':userName', $userName, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchObject();
if($result->no_found > 0)
{
return false;
}
Did you try:
$checkduplicates = "SELECT userName FROM usersexample
WHERE LOWER('".$userName."') = LOWER(userName)";
$myresult = mysql_query($checkduplicates)
if (!$myresult) {
die('Invalid query: ' . mysql_error());
} else {
$num_rows = mysql_num_rows($myresult);
if (!$num_rows) {
die('Invalid query: ' . mysql_error());
} else return ($num_rows == 0);
}
Please, sanitize user input to avoid SQL injection.
I don't know if you are doing something fancy I don't understand, but I would build the query like this:
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '$userName'";
Or this
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '".$userName."'";
Related
I'm working on something a bit more for myself, thats for another website that I own. It involves a lot of groups with permissions and such, and right now i have a function that looks like this
function hasPermission($user, $permission){
global $connection;
$sql = "SELECT * FROM admins WHERE `ID` = '". $user ."'";
$rs = $connection->query($sql);
if ($rs){
$user = $rs->fetch_array(MYSQL_ASSOC);
$userRank = $user['Rank'];
$sql = "SELECT * FROM `ranks' WHERE `RankName` = '". $userRank ."'";
$rs = $connection->query($sql);
if ($rs){
$rank = $rs->fetch_array(MYSQL_ASSOC);
if ($rank[$permission] == 1){
return true;
}
else{
return false;
}
}
}
else{
echo($connection->error);
}
}
Then when I call the function with the parameters set like this if (hasPermission($_SESSION['ID'], 'IsFullAccess') == true) it returns false, and I get my custom error message saying I don't have permission. And yes, in my database, the "IsFullAccess" column is set to 1 for that rank.
What am I doing wrong here?
After reading your code, it seems like you're not familiar with sql's JOIN:
your query looks something like this:
$sql= "SELECT r.$permission as p FROM admins a JOIN ranks r ON a.rank=r.RankName WHERE a.ID=$user";
$rs = $connection->query($sql);
if (!$rs)
return false;
$hasPermission = $rs->fetch_array(MYSQL_ASSOC);
return $hasPermission['p'];
(keep in mind sql injection)
Make sure that the db returns the result you expect before testing it within php
Try to use hasPermission($_SESSION['ID'], 'IsFullAccess') == 1) instead of hasPermission($_SESSION['ID'], 'IsFullAccess') == true). (true should be convert to 1)
I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}
I've got this code:
$query = 'SELECT * FROM users WHERE username = "' . $user . '" AND password = MD5("' . $pass . '") LIMIT 1';
echo $query;
$result = $mysqli->query($query);
echo "<br>Here: " . $result->num_rows;
Using the output from $query I put it into phpmyadmin and it returns 1 row but when trying to get the number of rows using num_rows it doesn't return anything at all - not even 0;
Any ideas?
http://ru2.php.net/manual/en/mysqli.query.php
Returns FALSE on failure.
Have you established a connectection to your DB?
Looks like the SQL query is messed up. As far as I know there is no MD5 function built into MySQL nor the SQL standard. Therefore if it does exist then it is probably proprietary to the particular DB.
That said you can use PHP to check it. Try this to see what is going on.
$encrypted_pass = md5($pass);
$query = "SELECT * FROM users WHERE username = '$user' AND password = '$encrypted_pass' LIMIT 1";
echo $query;
$result = $mysqli->query($query);
if ($result !== FALSE) {
echo "<br>Here: " . $result->num_rows;
}
else {
echo "Something is broken.";
}
Ref:
http://us2.php.net/manual/en/mysqli-result.num-rows.php
Simple piece of PHP code:
#login.php
$_SESSION['valid_user_id'] = getUserId($username, $password);
#user_auth_fns.php
function getUserId($username, $password)
{
$username = addslashes($username);
$username = mysql_real_escape_string($username);
$password = addslashes($password);
$password = mysql_real_escape_string($password);
$conn = db_connect();
$result = $conn->query("select id from user where username='$username' and password= sha1('$password')");
if (!$result) {
throw new Exception('Could not retrieve your user id.');
}
if ($result->num_rows > 0) {
return $result;
} else {
throw new Exception('Could not retrieve your user id.');
}
}
"return $result" is wrong, however I have no idea what I should put there in order to return the id from a certain user. The PHP manual didn't provide the answer either. I know this function works because replacing
return $result by return "test"
returns the correct value as expected.
if ($result->num_rows > 0) {
$row = mysql_fetch_row($result);
return $row['id'];
} else {
throw new Exception('Could not retrieve your user id.');
}
I would rewrite the whole function like so:
function getUserId($username, $password)
{
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$conn = db_connect();
$result = $conn->query("SELECT id FROM user
WHERE username = '$username'
AND password = sha2(CONCAT(user.salt,'$password'),512)");
if (!$result) {
throw new Exception('Could not retrieve your user id.');
}
if ($result->num_rows > 0) {
$row = mysql_fetch_row($result);
return $row['id'];
} else {
throw new Exception('Could not retrieve your user id.');
}
}
To prevent XSS
Before echoing any value from a database sanitize it:
echo htmlentities($row['username']);
Make sure you salt those hashes, or you will not be secure
Note that you will need to add a new field called SALT to your user table.
ALTER TABLE user ADD COLUMN salt INTEGER NULL default NULL;
Because the passwords are hashed, you will need time to translate them, use the following code to insert new entries:
INSERT INTO user (username, salt, password)
SELECT '$username', #salt, SHA2(CONCAT(#salt,'$password'),512)
FROM DUAL CROSS JOIN (SELECT #salt:= FLOOR(RAND()*99999999)) q;
And this code to test for valid passwords:
SELECT id, COALESCE(salt,-1) as salt FROM user
WHERE username = '$username'
AND CASE WHEN salt IS NULL
THEN password = SHA1('$password)
ELSE password = SHA2(CONCAT(salt,'$password'),512) END;
Update the user table like so when salt turns out be be -1.
UPDATE user
CROSS JOIN (SELECT #salt:= FLOOR(RAND()*99999999)) q
SET salt = #salt, password = SHA2(CONCAT(#salt,'$username'),512);
$result contains only the object of resulting rows. To access the data, you need to fetch the row from result.
With the mysqli library:
$result = $conn->query("select id from user where username='$username' and password= sha1('$password')");
$row = $result->fetch_object(); // or $row = $result->fetch_array();
return $row->id;
With the mysql library using array:
$result = $conn->query("select id from user where username='$username' and password= sha1('$password')");
$row = $result->fetch_assoc();
return $row['id'];
From php.net:
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
Try this:
if ($result->num_rows > 0) {
$tmp = $result->fetch_assoc();
$return = $tmp['id'];
return $return;
} else { ...
I don't know what DB wrapper you are using since you haven't shown us db_connect(), but I bet this will work:
$result = $conn->query(...);
$result = $result->fetch();
return $result['id'];
The value returned from $conn is probably an object representing a result resource, not actual rows. You need to fetch the rows from the resource as there are potentially more than one.
In my opinion, the main problem is that your function is returning the result object, while you actually had to return only the id field. In order to do that you had to fetch the row from the result object as object / array / associative array and return the id field from it. Just to illustrate my idea, in terms of native MySQL functions it would look something like this:
$res = mysql_query("SELECT id FROM usersTable WHERE username = '".mysql_real_escape_string($userName) . "' AND password = '" .mysql_real_escape_string($password) ."' LIMIT 1") or die("Cannot select id: ".mysql_error());
if(mysql_num_rows($res) > 0) {
$row = mysql_fetch_assoc($res); // fetch the retrived row as associative array, my personal favorite though others may prefer mysql_fetch_row or mysql_fetch_object instead
return $row['id']; // return the retrived id
}
else {
// your exception throwing code goes here
}
As a side note, do not see any sense in addslashes followed by mysql_real_escape_string since they are basically meant to do the same thing and mysql_real_escape_string is the preferred way to escape user input in database queries. So, I think you should just leave mysql_real_escape_string lines and get rid of addslashes stuff.
Is there any way to store mysql result in php variable? thanks
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
then I want to print selected userid from query.
Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
There are a couple of mysql functions you need to look into.
mysql_query("query string here") : returns a resource
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.
Links:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-array.php
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
$query="SELECT * FROM contacts";
$result=mysql_query($query);
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
http://php.net/manual/en/pdo.prepared-statements.php PDO
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.