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.
Related
I am not sure why it does not enter the if statement in the API class to actually execute the method. The goal of this method is to simply return a specific row of data, when entering a specific username (this is a users database that holds users info etc). Any help in the right direction is welcomed. This is fairly new stuff to me. Thanks
This is the Connect Class. It is working 100%
<?php
class DbConnect{
private $con;
function __construct(){
}
function connect(){
include_once dirname(__FILE__).'/Constants.php';
$this->con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect with database".mysqli_connect_err();
}
return $this->con;
}
}
<?php
This class handles all the functions.
EDIT: So after more testing, I believe the error is in this part of the code.
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function getTheSpecificUser($username){
//$username = $_POST['username'];
//$username = $_POST['username'];
$stmt= $this->con-> prepare("SELECT `id`, `username`, `email`,
`phonenumber`, `birthdate`, `lastname`, `firstname`, `middlename`
FROM `users` WHERE `username` = ?");
$stmt->bind_param("s", $username);
$stmt->bind_result( $id, $username, $email, $phonenumber,
$birthdate, $lastname, $firstname, $middlename);
$stmt->execute();
//$stmt->bind_result("isssssss", $id, $username, $email,
//$phonenumber, $birthdate,
//$lastname, $firstname, $middlename);
$results = array();
//$results = $stmt->fetch();
while($stmt->fetch()){
$result = array();
$result['id'] = $id;
//$result['username'] = $username;
$result['email'] = $email;
$result['phonenumber'] = $phonenumber;
$result['birthdate'] = $birthdate;
$result['lastname'] = $lastname;
$result['firstname'] = $firstname;
$result['middlename'] = $middlename;
array_push($results, $result);
}
return $results;
}
This is the class that handles all the operations.
This is where the method is called from DbOpertaions. It is included and works correctly with other functions.
EDIT: I do not think the error is here, because if the statement is taken out of the if statement, then it should fire, but nothing happens if added to $response. So again the error must be in the DbOperaitions class.
<?php
//getting the dboperation class
require_once '../includes/DbOperations.php';
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'getthespecificuser':
if(isset($_GET['username'])){
echo "you are past the frist if statement";
$db = new DbOperations();
if($db->getTheSpecificUser($_GET['username'])){
echo "you are in the second if statement";
$response['error'] = false;
$response['id'] = $user['id'];
$response['username'] = $user['username'];
$response['email'] = $user['email'];
$response['phonenumber'] = $user['phonenumber'];
$response['lastname'] = $user['lastname'];
$response['firstname'] = $user['firstname'];
$response['middlename'] = $user['middlename'];
}else{
echo "-->";
var_dump($_GET['username']);
die();
$response['error'] = true;
$response['message'] = "something went wrong";
}
}else{
$response['error'] = true;
$response['message'] = "please enter a valid username";
}
break;
}else{
//if it is not api call
//pushing appropriate values to response array
$response['error'] = true;
$response['message'] = 'Invalid API Call`enter code here`';
}
//displaying the response in json structure
echo json_encode($response);
I'm new with DB classes and working on it. I'm trying to make my old login system work with this DB class but it returns with my else for invalid login error, like there is no such e-mail and password in the DB. But there is.
Connection Class:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
Login Page:
<?php
include('dbConnect.php');
session_start();
$conexao = new Conexao("localhost", "root", "XXXXX", "festas");
if(isset($_POST['submit'])) {
$email = mysqli_real_escape_string($conexao,$_POST['email']);
$pass = mysqli_real_escape_string($conexao,$_POST['senha']);
$sel_user = $conexao->Query("SELECT * from contas where email='$email' AND senha='$pass'");
$check_user = mysqli_num_rows($sel_user);
$row = mysqli_fetch_assoc($sel_user);
if($check_user>0){
$_SESSION['user_email']=$email;
header('Location: ../adminpage.php');
mysqli_free_result($result);
} else {
header('Location: ../admin.php?erroLogin=1');
}
}
?>
Always it returns with the "else" header('Location: ../admin.php?erroLogin=1'). I think it could be because of "$check_user = mysqli_num_rows($sel_user);" but I tried to fix and can't. Tried also "$conexao->num_rows($sel_user).
I solved it. Here's what I did:
In DB class php:
public function Escape($sql)
{
return $this->link->real_escape_string($sql);
}
then in login php:
$email = $conexao->Escape($_POST['email']);
Thanks!
I'm try to return true from my getData method to be redirected after login to the homepage by $_SESSION['username'] but I'm always getting the error above. How can I make this method to work to return true?
<?php
class Login
{
private $host = "localhost";
private $user = "root";
private $db_password = "*****";
private $database = "*******";
private $db;
private $username;
private $password;
function __construct($username, $password)
{
// Set data
$this->setData($username, $password);
// connect to db
$this->connectToDb();
//get Data
$this->getData();
}
private function setData($username, $password){
$this->username = $username;
$this->password = $password;
}
private function connectToDb(){
// connect to the server.
$this->db = new mysqli($this->host, $this->user, $this->db_password);
if ($this->db->connect_errno) {
die("We are sorry, you could not be connected to the server,
plaese check your connection setting!");
}else{
echo "You are connected to the database";
}
}
private function getData(){
$query ="SELECT id FROM users WHERE username = '$this->username' AND
password = '$this->password'";
$stmt = $this->db->prepare($query);
$stmt->bind_param('ss', $this->username, $this->passowrd); //Hier is the error.
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->fetch();
$numberofrows = $stmt->num_rows();
echo '# rows: '.$numberofrows;
if ($numberofrows>1) {
return true;
}else{
throw new Exception("Please check your username and passowrd!");
}
}
}
?>
I appreciate any help.
Your query doesn't use placeholders, you should use
$query ="SELECT id FROM users WHERE username = '?' AND password = '?'";
example
I've seen the question asked but the answer wasn't very clear to me.
My code is.
index.php
<?php include 'header.php'; ?>
<?php
include "class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username1'];
$password = $_POST['password1'];
$users->login($username, $password);
}
?>
class.users.php
<?php
include "connect.php";
class Users extends Database {
public function login($username, $password) {
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
} else {
return false;
}
$stmt->close();
$stmt->free_result();
}
}
$users = new users();
?>
connect.php
<?php
class Database {
public function __construct() {
$host = 'localhost';
$user = 'root';
$pass = '';
$name = 'meeboo3';
$this->mysqli = new mysqli($host, $user, $pass, $name);
}
}
?>
The class Database isn't called twice? so how is it a error? can anyone explain why in the comments.
you could test to see if its already declared before doing so:
if (!isset($database) && !is_a($database, 'Database')){
$database = new Database();
}
Or
if you're declaring it inside connect.php you could:
include_once 'connect.php';
instead of
include 'connect.php';
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();