I am trying to use a function to get the password of the user based on the username that is entered. However I can not seem to get the result to be a string. How to i transfer it to a string? I just want the value that is stored in the password column.
here is the function
public function get_password($username) {
global $pdo;
$query = $pdo->prepare("SELECT `password` FROM `users` WHERE `username` = ?");
$query->bindValue(1, $username);
$query->execute();
$query->fetch(PDO::FETCH_ASSOC);
return $query;
}
i want this because i keep getting a error saying that a parameter that uses the result from this function expects string, array given, so i assume the result from the function needs to be a string not an array
EDIT: I tried adding $query['password'] but it returned an error that said Cannot use object of type PDOStatement as array
Use this:
public function get_password($username) {
global $pdo;
$query = $pdo->prepare("SELECT `password` FROM `users` WHERE `username` = ?");
$query->bindValue(1, $username);
$query->execute();
$password = "";
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$password = $row['password'];
}
return $password;
}
try this
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$password = $row['password'];
}
Related
I am student and I work on a noteapp. I made 2 methods in my DB-Handler within my Login-Mask for users to Login or Register.
<?php
class DBHandler
{
var $hostname;
var $user;
var $pw;
var $db;
var $connection;
function connectToDB($hostname,$user,$pw,$db){
$this->hostname = $hostname;
$this->user = $user;
$this->pw = $pw;
$this->db = $db;
$this->connection = new mysqli($this->hostname,$this->user,$this->pw,$this->db);
if ($this->connection->connect_error) {
die('Failed to connect' . $this->connection->connect_error);
}
$this->ensureNotesTable();
$this->ensureUsersTable();
}
function ensureUsersTable(){
assert($this->connection);
$queryCreate = "CREATE TABLE IF NOT EXISTS users(id INT(5) PRIMARY KEY AUTO_INCREMENT, username VARCHAR(100) NOT NULL, password VARCHAR(100) NOT NULL)";
$this->connection->query($queryCreate);
}
function ensureNotesTable(){
assert($this->connection);
$queryCreate = "CREATE TABLE IF NOT EXISTS notesnew(id INT(5) PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, content VARCHAR(100) NOT NULL, userid INT(5) NOT NULL)";
$this->connection->query($queryCreate);
}
function ensureUsername($username,$password){
assert($this->connection);
echo $username;
$query = "SELECT * FROM users WHERE username = (?)";
$statement = $this->connection->prepare($query);
$statement->bind_param('s',$username);
$results = $statement->execute();
echo $this->connection->errno.'-'.$this->connection->error;
if(mysqli_num_rows($results) >= 1){
echo $this->connection->errno.'-'.$this->connection->error;
echo "Username already exists";
} echo "Username is free!";
$this->addUser($username,$password);
}
function addUser($username,$password){
assert($this->connection);
$queryCreate = "INSERT INTO users(username, password) VALUES (?,?)";
$statement = $this->connection->prepare($queryCreate);
$statement->bind_param('ss', $username, $password);
return $statement->execute();
echo "You have been registered!";
}
function getUserId($username){
assert($this->connection);
$queryCreate = "SELECT id FROM users WHERE username = $username";
$row = $this->connection->query($queryCreate);
$userid = mysqli_fetch_row($row);
return $userid[0];
}
function addNote($title, $text, $userID){
assert($this->connection);
$queryCreate = "INSERT INTO notesnew(title, content, userid) VALUES (?,?,?)";
$statement = $this->connection->prepare($queryCreate);
$statement->bind_param('ssi', $title,$text,$userID);
return $statement->execute();
}
}
Within ensureUsername I wanna check if the username which is used for the registration has already been picked by another user.
Within addUser I wanna do the Insert statement, to add the user to the database, if the username is free.
I tried about 3 hours today but it always gives me errors. I hate it! Maybe im just too stupid for it.
At the moment its saying:
Warning: mysqli::query() expects parameter 1 to be string, object
given in
C:\Users\ReallySorry\PhpstormProjects\NoteAppMongo\DBHandler.php on
line 57 0- Warning: mysqli_num_rows() expects parameter 1 to be
mysqli_result, null given in
C:\Users\ReallySorry\PhpstormProjects\NoteAppMongo\DBHandler.php on
line 60
Does anybody know what im doing wrong?
Thanks ...
The depressed student
Your problem is here:
$statement = $this->connection->prepare($query);
$statement->bind_param('s',$username);
$results = $this->connection->query($statement)
When you're using prepared statements (well done – so many people here don't!) you need to use the execute() method on your statement rather than calling query() on your connection. So, this should work:
$results = $statement->execute()
Some minor changes to the original -
function ensureUsername( $username=false, $password=false ){
$rv=false;/* Return Value */
if( !assert( $this->connection ) or !$username or !$password ) return $rv;
$db=$this->connection;/* shorthand for laziness */
$sql = "select `username` from `users` where `username`=?;";
$stmt = $db->prepare( $sql );
$stmt->bind_param('s', $username );
$res = $stmt->execute();
$stmt->store_result();
if( $res ){
$rv=( $stmt->num_rows > 0 ) ? 'Sorry, that Username already exists!' : $this->addUser( $username, $password );
}
$stmt->free_result();
$stmt->close();
echo $rv;
}
function addUser( $username, $password ){
$db=$this->connection;/* No need for assert now, if the script gets here the db conn must exist */
$sql = "insert into `users` (`username`, `password`) values (?,?);";
$stmt = $db->prepare( $sql );
$stmt->bind_param('ss', $username, $password );
return $stmt->execute() ? 'You have been registered!' : 'Sorry, there was a problem';
}
I have this php login function that doesn't seem to work with a hashed password in my database.
Where var_dump is, it return both values of the hashed password and the member id.
If I move the var_dump after the second if, it will not return anything. Any suggestions?
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT member_id, member_first_name, member_password FROM members WHERE member_id = ? ");
$stmt->bind_param('i', $id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbMember_id = $row['member_id'];
$dbMember_first_name = $row['member_first_name'];
$dbpassword = $row['member_password'];
}
if($id == $dbMember_id)
{
var_dump($dbpassword);
var_dump($dbMember_id);
if(password_verify($password,$dbpassword))
{
session_start();
$_SESSION['session_member_first_name'] = $dbMember_first_name;
$_SESSION['session_member_id'] = $dbMember_id;
$_SESSION['last_acted_on'] = time();
}
}
}
}
Thanks
I am trying to write a parametrised login function in PHP.
The function should get the $id and $pass bind and execute statement and return an associative array from the database with $id, $password, $user_first_name.
Checking for user id and password validation, if true the session should start and set the session with the username from the database.
For some reason I can't get this working. Any suggestions?
Thanks!
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT user_id, user_name, user_password FROM Users WHERE user_id = ? ");
$stms->bind_param('i', $user_id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbuser_id = $row['user_id'];
$dbpassword = $row['user_password'];
$dbuser_first_name = $row['user_first_name'];
}
if($id == $dbuser_id and $password == $dbpassword)
{
session_start();
$_SESSION['session_user_first_name'] = $dbuser_first_name;
}
else
{
session_unset();
echo "Credentials do not match";
}
}
}
You have
$stms->bind_param('i', $user_id);
But your function signature is:
public function logIn($id, $password)
So you probably want:
$stms->bind_param('i', $id);
Have a look at $stms->bind_param('i', $user_id);:
stms should be stmt
$user_id should be $id
...
I create this class but i'm newbie in PHP OOP & PDO and i don't know how and where i must to make check to username is valid , email is valid and e.t.c..
This is my code
Class Users {
private $db;
public function __construct(Database $datebase) {
if (!$database instanceOf Database) {
throw new Exeption();
}
$this->db = $datebase;
}
public function userRegistration($username, $password, $email) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$regdate = date('d.m.Y');
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `regdate`) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $regdate);
return ($query->execute()) ? true : false ;
}
}
If you want to check something, use Respect/Validation. For example:
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate($_POST['username']); //true or false
$passwordValidator = v::alnum()->length(10, null);
$passwordValidator->validate($_POST['password']); //true or false
v::email()->validate($_POST['email']); //true or false
To check if the username or email exist in your database you can use SQL to search the email or username.
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
If the query returns a value than the email or username already exist in your database. From there you can show your own validation.
To check check if user or email exist you don't need another class, just add another method called userExist or emailExist and run a query and then check if you get a result.
public function emailExist($email){
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
try{
$query->execute();
//use the if statement and $query->rowCount() to check if there is a result
$rows = $query->rowCount();
if($rows === 1){
return true;
} else {
return false;
}
}catch (PDOException $e) {
die($e->getMessage());
}
}
I'm creating a PDO class to use on my projects, but since I'm new to it I'm not being able to bind parameters to a prepared sql statement, with not error whatsoever. Here's the function that is ment to do it :
# ::bindParam
public static function bind()
{
# get function arguments
$args = func_get_args();
# check for any arguments passed
if (count($args) < 1)
{
return false;
}
foreach ($args as $params)
{
# named variables for convenience
$parameter = $params[0];
$variable = $params[1];
$data_type = isset($params[2]) ? $params[2] : PDO::PARAM_STR;
$length = isset($params[3]) ? $params[3] : null;
# bind param to query
Database::$statement->bindParam($parameter, $variable, $data_type, $length) or die('error');
}
}
and a prepared sql statement :
SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1
Can someone point me in the right direction? The query produces no errors at this point. Note that I am assuming the problem is here, although it might not, since I'm only using bindParam() and prepare().
edit - trigger code
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$this->db->prepare('SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1');
$this->db->bind(
array(':email', $email),
array(':password', $password)
);
$status = $this->db->execute();
if ($status)
{
$result = $this->db->fetch('assoc');
$this->template->user = $result;
}
else
{
$this->template->user = false;
}
As #YourCommonSense already mentioned, raw PDO interface is a little bit clearer, however the problem is probably due to the use of function PDOStatement::bindParam() instead of PDOStatement::bindValue().
The difference between those two is that, the first one takes a variable reference, which is constantly overwritten in your foreach loop, while the last one takes the actual value of the variable.
If you're looking for some more friendly database connection interface, why won't you try Doctrine DBAL?
Just get rid of this function, PDO already has it
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$this->db->prepare('SELECT * FROM `users` WHERE `email` = :email AND `password` = :password LIMIT 1');
$stmt = $this->db->execute(array(':email'=> $email,':password' => $password));
$this->template->user = $this->db->fetch();
That's all code you need (assuming your class' execute is a regular PDO execute)
Or, to make it in raw PDO:
$email = $_POST['email'];
$password = $_POST['password'];
$password = hash('sha256', $password);
$sql = 'SELECT * FROM users WHERE email = ? AND password = ? LIMIT 1';
$stmt = $this->db->prepare($sql);
$stmt->execute(array($email, $password));
$this->template->user = $stmt->fetch();
So, it seems your class require more code than raw PDO. Are you certainly sure you need this class at all?