PHP return id from select - 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.

Related

PHP code mysql query isnt working

I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.

PHP How to check if a string already exists in a MySQL table

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());
}

search SQL for possibly duplicated user names using PHP

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."'";

mysql query result in php variable

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.

Creating a variable by pulling a value from a MySQL database

I am using a MySQL table called "login" that includes fields called "username" and "subcheckr."
I would like to run a PHP query to create a new variable equal to "subcheckr" in the table where "username" equals a variable called $u. Let's say I want to call the variable "$variable."
How can I do this? The query below is what I have so far.
Thanks in advance,
John
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
I don't know if I understood correctly but if:
Just do something like this.
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
In case you don't know, your query is vulnerable for SQL injections. Use something like mysql_real_escape() to filter your $u variable.
Is this what youa re looking for?
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$subcheckr = $row['subcheckr'];
$sqlStremail = mysql_query("SELECT subcheckr FROM login WHERE username = '$u'");
$result= mysql_fetch_array($sqlStremail);
$some_variable = $result['subcheckr']; // the value you want
You can do:
// make sure you use mysql_real_escape to escape your username.
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
// run the query.
$result = mysql_query($sqlStremail );
// See if the query ran. If not print the cause of err and exit.
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
// if query ran fine..fetch the result row.
$row = mysql_fetch_row($result);
// extract the field you want.
$subcheckr = $row['subcheckr'];
You can write
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
$result = mysql_query($sqlStremail );
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$row = mysql_fetch_row($result);
$subcheckr = $row['subcheckr'];
$variable = array_pop(mysql_fetch_row(mysql_query("SELECT subcheckr FROM login WHERE username = '$u'")));
Only if username is unique

Categories