user_exists function using mysqli - php

I';m working on changing my code from using MySQL to MySQLi, and its all seemed to be going fine, but I hit a bit of a wall, I'm currently stuck on changing over my function user_exists and I have tried looking into different reason why and what's going wrong but it seems to be the query, i did var_dump($result) and got the response NULL and was told that its down to my query then, so i tried an sql search on phpmyadmin and got a result so im thinking its down to me binding $username to the ? as the errors i get is of that it cannot find the username im trying to log in with.
function user_exists($username) {
$db = $GLOBALS['db'];
$username = trim($username);
//sql
$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//Bind-Results - the 2 codes below are noted out cause im not sure they are needed but have tried with and without them
//$result->bind_result($user_id);
//$result->fetch();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
i can provide the code to my signin.php but im not sure it would be useful as it all worked before i started changing the function.
if someone could point out what, where and why its not working, can you please explain so i can understand so Im good for the future and maybe able to help others out.

You need to call $result->store_result() before checking the number of rows. mysqli_stmt::store_result() will load the result set from the prepared statement so you can access results and properties.
EDIT: This is sort of how I would do it though (untested):
function user_exists($username) {
global $db;
//sql
$sql = "SELECT `user_id` FROM `users` WHERE `username` = ?";
//Prepare
if (!($result = $db->prepare($sql)) return false;
//Bind
if (!$result->bind_param('s', trim($username))) return false;
//execute
if (!$result->execute()) return false;
//Bind-Results
$result->bind_result($user_id);
$result->fetch();
$result->close();
return $user_id ?: false;
}

Here is how my user_exist() function ended up
function user_exists($username) {
$db = $GLOBALS['db'];
//sql
$sql = "SELECT user_id FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//store result
$result->store_result();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
I hope this will help someone. But if any of the code shouldn't be there, i apologise in advance, the code was there for a reason at one point but as im learning all this still, no one advised me that it shouldnt be there.. hope it helps

Related

Php use of bindParam in SQLite

When I try to add something to the sqlite databse the result is always false. Where is the error? I don't get an exception so I think the code is correct by syntax. Please help me
public function add(ChatMessage $chatMessage){
$stmt = $this->db->prepare('INSERT INTO chatmessage(id,authorName,message) VALUES(:id,:authorName,:message)');
$stmt->bindParam(':id',$id);
$stmt->bindParam(':authorName',$authorName);
$stmt->bindParam(':message',$message);
$id = $chatMessage->getID();
$authorName = $chatMessage->getAuthorName();
$message = $chatMessage->getMessage();
$result = $stmt->execute();
if($result == false) return false;
$chatMessage->setID($this->db->lastInsertId());
$chatMessage->setAuthorName($this->db->lastInsertId());
$chatMessage->setMessage($this->db->lastInsertId());
$this->chatMessages[]=$chatMessage;
}

Get a value from database using PDO php

I read few topics about my issue here and it didnt solve anything..
I don't understand where I am wrong in my code..
So I need to get the name from a database when my vt_id equal a number..
function recup_nom_visite($VT_ID){
$pdo = PDO2::getInstance();
$requete = $pdo->query("SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID = :vt_id ");
$requete->bindValue(':vt_id' , $VT_ID);
$requete->execute();
if($result = $requete->fetch(PDO::FETCH_ASSOC)){
$requete->closeCursor();
return $result['NOM_VISITE'];
}
return false;
}
I tried this too :
function recup_nom_visite($VT_ID){
$pdo = PDO2::getInstance();
$requete = $pdo->query("SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID ='".$VT_ID."' ");
$req = $requete->fetch();
$result = $req;
return $result;
}
but all result it returns is "array" or nothing..
Do I miss something ?
Thank you for help
function recup_nom_visite($VT_ID){
$sql = "SELECT VT_NOM FROM CRF_VISITE WHERE VT_ID = ?";
$stmt = PDO2::getInstance()->prepare($sql);
$stmt->execute(array($VT_ID));
return $stmt->fetchColumn();
}
This is how PDO intended to work.
PS. Do not delete your questions. Deleted question cannot be answered, you know.

I can't get result from mysqli query with PHP (converted from mysql_result)

I have a PHP function that I am converting from using the mysql extension to the mysqli extension.
Everything is going okay, until here. I previously used a mysql_result to get a single piece of data. There is no direct equivalent in mysqli, so I have tried the following but it still doesn't work.
function getdbvalue($table,$value,$idfield,$id) {
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
I have verified that the variables are passing to the function okay, and the function is actually getting triggered. If I return $id I see the ID numbers.
I don't get an error for the query.
SOLVED:
I needed to add the database connection variable as a global in the function:
Working code:
function getdbvalue($table,$value,$idfield,$id) {
global $dbh; // This was missing!
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
Thanks to everyone for their help. :)
Although it's good idea to automate simple selects, the implementation is highly insecure, and should never be used.
Make it accept SQL query and parameters. It will make it secure.
And also you have to use PDO instead of mysqli
function getdbvalue() {
global $pdo;
$args = func_get_args();
$sql = array_shift($args);
$stm = $pdo->prepare($sql);
$stm->execute($args);
return $stm->fetchColumn();
}
have to be used like this (you have to connect to PDO first):
$name = getdbvalue("SELECT name FROM users WHERE id=?", $is);
this is the only proper way

How to successfully login on webpage using SHA1 + PDO + Prepared Statement?

I am fighting now like hours to figure out how to make possible to use SHA1 + PDO + Prepared Statement combination and still be able to log in to web page :) So my question is how to do so? Here is my code:
if (!empty($user) && !empty($password))
{
$password = $this->doHash($user, $password);
$stmt = $db_login->prepare("SELECT COUNT(*) FROM account WHERE username=:user AND sha_pass=:password");
$stmt->bindValue(':user', $user, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
$results_login = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results_login['COUNT(*)'] > 0)
{
$_SESSION['user_name'] = $results_login['username'];
$_SESSION['user_id'] = $results_login['id'];
return true;
}
else
{
return false;
}
}
else
{
return false;
}
My function doHash looks like this:
public function doHash($user, $password)
{
return sha1(strtoupper($user).":".strtoupper($password));
}
So my problems are: $results_login*** never processes with the SELECT COUNT(*) version, and with SELECT * version it processes sometimes, but not always. So how do I put it together to work as intended, result in true, and fill all the variables I need? Thank you.
Your SQL statement is only counting, it is not selecting the username and id, you would need to use this as your SQL statement, or something like it:
"SELECT * FROM account WHERE username=:user AND sha_pass=:password"
For your password binding, the following should work just fine. I would also use rowCount and only fetch, not fetchAll. Give this a try and see if it works.
$stmt->bindValue(':password', doHash($user,$password), PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()==1){
$results_login=$stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_name'] = $results_login['username'];
$_SESSION['user_id'] = $results_login['id'];
return true;
}else{
return false;
}

can't bind parameter properly in mysql script

Hey I'm learning a new way of querying my databases because its meant to be better and more secure, this i building prepared statements that can be reused.
The problem is this is a different way of looking at it and im not used to it yet and still have some things that aren't clear to me.
So my script tries to bind three paras to a query to allow a user to login to my site. I am using the same script as before, this used user name and password... This works just fine:
$query = "SELECT *
FROM user
WHERE email = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query))
{
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch())
{
//$uid = $stmt->fetch(id);
//$_SESSION['uid'] = $uid;
$stmt->close();
return true;
}
}
but when i check if the user is admin i doesn't like it at all:
$query = "SELECT *
FROM user
WHERE email = ? AND password = ? AND isAdmin = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query))
{
$stmt->bind_param('ssi', $un, $pwd, $isAdmin);
$stmt->execute();
if($stmt->fetch())
{
//$uid = $stmt->fetch(id);
//$_SESSION['uid'] = $uid;
$stmt->close();
return true;
}
}
Also i declare isAdmin as a global private var at the start of the class like so:
private $isAdmin = "1";
So yeah i know that the user i am testing has a 1 for isActive on the database but when it does into this script it returns false.
Like i said i'm new to this style of writing queries so any help would be amazing.
Thanks for the time.
Okay so i think i've got it. I added the isActive var to the function that is using it instead of it being global now it works fine.
Thanks for you help. Any other tips on the matter would be more than welcome!

Categories