Getting user and encrypted password from datebase - php

i got the following code:
public function getUserByNameAndPassword($name, $password) {
$stmt = $this->conn->prepare("SELECT salt FROM `users` WHERE name = ?");
$stmt->bind_param("s", $name);
if ($stmt->execute()) {
$stmt->store_result();
$salt = $stmt->get_result();
}
$encryptedpassword = $this->checkhashSSHA($salt,$password);
$stmt = $this->conn->prepare("SELECT * FROM `users` WHERE name = ? AND encrypted_password = ?");
$stmt->bind_param("ss", $name, $encryptedpassword);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}
else {
return false;
}
}
And the following constructor:
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
I'm trying to get user from datebase but it is not working at all, i already tried many things, checked my syntax multiple times but i can't find my mistake. Anybody has an idea?
Edit: Changed code and added log but the log doesent report anything.

Related

Issue with PDO Connection

i am new to this so dont be rude :D
I have 3 file: database.php, init.php and user.php
Here the init.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require 'database.php';
require 'functions/user.php';
$errors = array();
Here the database.php:
<?php
$db_host = "localhost";
$db_name = "xxxx";
$db_user = "xxxx";
$db_pw = "xxxx";
try {
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw);
} catch(PDOException $e) {
die("Verbindung fehlgeschlagen: " . $e->getMessage());
}
And here the user.php:
<?php
function userExists($user) {
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
So the error message:
Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4
The function userExists() is called in another file named login.php. In login.php i have already required init.php. The error message appears when i want to login.
So i hope you can help me.
Thx
$conn is not available in your function since it is in a different scope. Pass it as a parameter or declare it as a global variable.
function userExists($user, $conn){
// ...
}
or
function userExists($user){
global $conn;
// ...
}
In your userExists function you are calling $conn variable which isn't global scope (Give a small look here)..
You can use one of these:
function userExists($user, $conn){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
function userExists($user){
global $conn; //<--- bad practi
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
use of $GLOBALS variable
function userExists($user){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

retrieve values mysqli_fetch

I'm trying to get the id value from a table called usuario in the database, passing $username as parameter, the function $conexion->connect() returns a mysqli object. The functions give me no errors but it doesn't return the value from database. Am I missing something? or making any mistake.
Thanks for help.
public function checkUserNameExists($username){
$conexion = new Connection();
$conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conexion->connect()->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
This is the function connect() what is located in a class file "Connection"
public function connect(){
$mysqli = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli
}
public function checkUserNameExists($username){
$conexion = new Connection();
$conn = $conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conn->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
You should store the return value of new mysqli in a variable, and then use that variable to make queries or prepares from.

Check user credentials PHP MySQL

Im trying to create a user management section on my website that allows users to login.
So far I have the following PDO Conenction class...
<?php
class connection{
private $host = 'localhost';
private $dbname = 'dbname';
private $username = 'liam#';
private $password ='Password';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
?>
My check-login.php looks like...
<?php
include 'assets/connection.class.php';
$username=$_POST['username'];
$password=$_POST['password'];
function login(PDO $db, $username, $password) {
$user_id = user_id_from_username($db, $username);
$password = md5($password);
$stmt = $db->prepare('SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ? AND `password` = ?');
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->execute();
if($stmt->fetchColumn() > 0) {
return $user_id;
} else {
return false;
echo 'failed';
}
}
?>
my problem is that im not given any result from check-login.php? Im not a php programmer so apologies if this seems vague, any help will be appreciated
It could be a problem with
$user_id = user_id_from_username($db, $username);
Since we don't know what that function (user_id_from_username) is doing, it might be that the
return $user_id;
is just returning NULL or an empty string.

MySQLi Prepared Statement Query Issue

I'm relatively new to MySQLi prepared statements, and running into an error. Take this code:
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->query("SELECT * FROM members WHERE username='$user' AND password='$pass'"))
{
echo $stmt->num_rows;
}
This will display "1", as it should.
This next piece of code though, returns "0":
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
echo $stmt->num_rows;
}
Any ideas why?
you need to call store_result() before you get the number of rows
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
$stmt->store_result(); // add this line
echo $stmt->num_rows;
}

Categories