Put ID before return function - php

In following code I have upgraded function from MYSQL into MYSQLI, I got some help in my previous posts and they said what should be done.. but now comes the question how to do it..
The thing is to set id before return, otherwise I still will be receiving user ID = 1 no matter on which account I login.
function user_id_from_username($username) {
$username = sanitize($username);
global $db_connect;
$result = $db_connect->query("SELECT(id) FROM members WHERE username = '$username'");
if (false === $result) {
return false;
}
return ($result->num_rows == 1) ? id : false;
I tried to do as in my old MYSQL code, but then it gives error.
My old code:
function user_id_from_username($username){
$username = sanitize ($username);
return mysql_result(mysql_query("SELECT(id) FROM members WHERE username = '$username'"), 0, 'id');
}
I would be grateful for any help!

I didn't try it out but this should work right?
I also put $db_connect as parameter because its safer but it's up to you.
function user_id_from_username($username) {
$username = sanitize($username);
global $db_connect;
$result = $db_connect->query("SELECT id FROM members WHERE username = '".$db_connect->real_escape_string($username)."'");
if (!$result) {
return false;
}
if($result->num_rows == 1){
$row = $result->fetch_assoc();
$output = $row['id'];
}
else{
$output = "Username does not exist in table or is a duplicate.";
}
return $output;
}

Did you try fetch_array or mysqli_fetch_array?
$row = $result->fetch_array(MYSQLI_ASSOC);
// or
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// and returning
return $row['id'] ? $row['id'] : false;

return ($result->num_rows == 1) ? id : false;
should be
if(mysqli_num_rows($result) ===1 ){
$row = mysqli_fetch_assoc($result);
return intval($row['id']);
}
return false;

Related

Register & Login code does not work

I've been working on a login/register system like in this video: https://www.youtube.com/watch?v=Til3oVNlho4&index=7&list=PLE134D877783367C7, but the problem is that it is using Mysql rather than Mysqli functions which makes it almost impossible to understand to me as a beginner. Basically, I`m stuck at database checking if "user_exists" function. Would anyone be able to point me to the right direction?
<?php
function user_exists($username) {
include 'core/database/connect.php';
$username = sanitize($username);
$sql = "SELECT COUNT(user_id) FROM `users` WHERE username = '$username'";
$query = mysqli_query($db, $sql);
return (mysqli_result($query, 0) == 1) ? true : false;
}
function mysqli_result($res,$row=0,$col=0) {
$numrows = mysqli_num_rows($res);
if ($numrows && $row <= ($numrows-1) && $row >=0){
mysqli_data_seek($res,$row);
$resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
if (isset($resrow[$col])) {
return $resrow[$col];
}
}
return false;
}
?>
Then I`m doing a check if that user exists:
if (user_exists('bill') === true) {
echo 'exists';
} else {
echo 'not ok';
}
It is always returning as not true even if the user is in my database.
function user_exists($username) {
include 'core/database/connect.php';
$username = sanitize($username);
$sql = "SELECT user_id FROM `users` WHERE username = '{$username}'";
$result = mysqli_query($db, $sql);
$num_rows = mysqli_num_rows($result);
return $num_rows > 0 ? true : false;
}
Try that, you don't need second function. This piece of code does not check for validation or implements try/catch blocks. I modified your SQL statement because you just need to see if the result returned anything higher than zero results.
The condition for $numrows always evaluates to 0. Therefore it returns false and hence not true.

How to set either profile name else user name in my php code

I want show my message system user Profile name(If have) else show user name.
In my every code I used as below, which work well.
if (empty($pname)) $pname = $username;
But in below I cannot understand how to Return 'profile name else user name' in my "function getusername($userid)".
Here if I use return $row[0] at my "function getusername" Its show username, But I want to show Profile name and If profile name empty then show user name.
Get profile name/user name code:
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
} else {
return "Unknown";
}
}
This code fetch a specific message
function getmessage($message) {
$sql = "SELECT * FROM mail WHERE `id` = '".$message."' && (`from` = '".$this->userid."' || `to` = '".$this->userid."') LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
// reset the array
$this->messages = array();
$row = mysql_fetch_assoc($result);
$this->messages[0]['id'] = $row['id'];
$this->messages[0]['title'] = $row['title'];
$this->messages[0]['message'] = $row['message'];
$this->messages[0]['from'] = $this->getusername($row['from']);
$this->messages[0]['to'] = $this->getusername($row['to']);
} else {
return false;
}
}
Use this
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $pname;
} else {
return "Unknown";
}
}
The problem is with how you are returning the value.
Change:
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
To:
if(empty($pname)) return $username;
else return $pname;
Also, it is suggested you use mysqli instead of mysql.
Can't you use something like this?
return isset($pname) ? $pname : $username;
This basically is: if $pname is set, then return $pname, else return $username

strpos always returning true

My code always return "true" whatever the string is I tried a bunch of thing but they are only return false... I have no idea what I can do to fix this... my code:
public function isBlacklisted($string)
{
$apis = mysql_connect("mysql.hostinger.fr", "mysql user", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM blacklist";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
if (strpos($string,$username) !== 0) {
return true;
break;
} else {
return false;
break;
}
}
}
strpos returns false is it is not found, and 0 if it is in the first position of the string. It sounds like you want to do:
if (strpos($string,$username) !== false) {
Also, you are looping over the DB results, you should only return if it is found:
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
if (strpos($string,$username) !== false) {
return true;
}
}
return false;
Or, even better:
$sql = "SELECT * FROM blacklist WHERE 'username' LIKE '%$username%'";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['username']) return true;
}
making sure to escape $username and ideally switching to mysqli or pdo instead of using deprecated mysql statements.

Function giving correct answer in one case, not in any others

Below is the function I am using. It is strange because when I test the name "admin" it returns an associative array with all the correct columns and values, however every other name tests returns 0 as far as I can tell, meaning nothing is found from the query (I am entering the names perfectly as they are in the database).
I have a feeling this could be some sort of security feature of pdo or something but I don't understand why it is acting up this way.
I am using mysql.
Does anyone know the problem and how to resolve it? Thank you!
function getUserDetailsByName($name, $fields = "*")
{
$db = connect_db();
$query = "SELECT $fields FROM UserDetails WHERE userName=:username";
$result = $db->prepare($query);
$result->bindParam(":username", $name);
if (!($result->execute())) {
sendMessage (1,1,'Query failed',$query);
$db = null;
return;
}
if (!($result->fetch(PDO::FETCH_NUM) > 0)) {
$db = null;
return 0;
}else{
$result = $result->fetch();
$db = null;
return $result;
}
}
EDIT: Someone asked to post how I call the function.
$user = getUserDetailsByName($_POST['value']);
if($user == 0)
{
print "user = 0";
}
print_r($user);
function getUserDetailsByName($name, $fields = "*"){
$db = connect_db();
$query = "SELECT {$fields} FROM UserDetails WHERE userName = :username LIMIT 1;";
if(!$result = $db->prepare($query)){
return null;
}
$result->bindParam(":username", $name);
if(!$result->execute()) {
sendMessage (1,1,'Query failed',$query);
return null;
}
if(!$user = $result->fetch(PDO::FETCH_NUM)) {
return false;
}
return $user;
}
Why 2 fetches? Checkout and compare this to your code.
Use like this:
if($user = getUserDetailsByName($_POST['value'])){
// we have a user!
}else{
// we don't have a user!
}

Reason for: Trying to get property of non-object in php

if(isset($_POST['uname']))
{
$query = "SELECT * FROM user_info";
$res = $mysqli->query($query);
$num = $res->num_rows;
$i = 0;
$cpwd = $_POST["pswd"];
$hpwd = SHA1($cpwd);
$tmp = $_POST["uname"];
while($i < $num)
{
$row = $res->fetch_object();
$name = $row->Username;
$pwd = $row->Password;
if($name == $tmp)
{
//check if user is blocked
}
//hashed pwd
if($pwd == $hpwd)
{
//success
exit();
}
//request for pwd change
else if($pwd == $cpwd)
{
//change
exit();
}
else if($pwd != $hpwd)
{
//incorrect pwd
}
}
$i++;
}
if($i == $num)
{
//new user
}
}
I'd guess that you're somehow looping past the end of the array and $row is actually NULL.
So $res->fetch_object() did not return an object. Take a look at the documentation of this function. What does it return when it finds nothing?
some times num_rows return 1, even if no rows effected. Try to use
while($row = $res->fetch_object())
or
you forget to increment $i :)
get rid of that junk and make it like this
$query = "SELECT * FROM user_info WHERE Username = ? AND Password = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $_POST["uname"], SHA1($_POST["pswd"]));
$stmt->execute() or trigger_error($mysqli->error());
if (!$mysqli->affected_rows) {
//no such user
}
I've never used mysqli myself, so, there may be typos.
But I hope you'll be able to get the idea.

Categories