Login Function [PHP][PDO] - php

I've been having trouble trying to get my login function to work. Whenever I try to login it always gives me this Syntax error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cereal_mod\includes\Cereal.php on line 53
I'm not sure if the Database connection is part of the problem but i'm not totally sure what's the big ideal of it not operating correctly.
Here is Database.php
<?php
namespace Cereal;
ini_set('error_reporting', E_ALL);
class Database Extends \PDO
{
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
try
{
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = parent::prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
?>
Here is the login.php
<?php
ini_set('error_reporting', E_ALL);
include "includes/Cereal.php";
$manager = new Cereal;
session_start();
if(isset($_POST['username'], $_POST['password'], $_POST['submit'])){
$login = $manager->login($_POST['username'], $_POST['password']);
}
?>
<form action="" method="POST">
<div id="login">
<input type="username" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</div>
and lastly Cereal.php
<?php
#namespace Cereal;
ini_set('error_reporting', E_ALL);
class Cereal {
private $configObj;
private $databaseObj;
public $playerData;
public function __construct(){
$this->loadConfig();
if($this->configObj){
try {
$dbHost = $this->configObj['Database']['Host'];
$dbName = $this->configObj['Database']['Database'];
$dbUser = $this->configObj['Database']['User'];
$dbPass = $this->configObj['Database']['Pass'];
$this->databaseObj = new Database('mysql:host=' . $dbHost . ';dbname=' . $dbName, $dbUser, $dbPass);
} catch(\PDOException $ex){
$this->__return($ex->getMessage, true);
}
}
}
private function loadConfig(){
$configPath = getcwd() . '/includes/config/Configuration.json';
$configData = file_get_contents($configPath);
$configObj = json_decode($configData, true);
if(!$configObj){
$this->configObj = $configObj;
} else {
}
}
public function __return($message, $die = false){
$successCheck = $die ? 'false' : 'true';
$messageArr = Array('success' => $successCheck, 'message' => $message);
echo json_encode($messageArr);
if($die) die();
}
public function login($username, $password){
try {
$login = $this->databaseObj->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$login->bindParam(':username', $username);
$login->bindParam(':password', md5($password));
$login->execute();
$row = $login->fetch(PDO::FETCH_ASSOC);
if($row) {
$_SESSION['auth'] = 1;
$_SESSION['username'] = $username;
die(json_encode(array("error"=>false, "message"=>"")));
} else {
die(json_encode(array("error"=>true, "message"=>"Incorrect credentials")));
}
} catch(PDOException $e) {
error_log('PDOException: ' . $e->getMessage());
die(json_encode(array("error"=>true, "message"=>"Database error, this has been logged.")));
}
}
}
?>
If someone could point out what i'm doing wrong I would really appreciate that because I haven't played with PDO in a while and i'm not sure if I am doing this correctly.

In Database.php you need to change
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
}
to
public function __construct($dsn, $dbUser, $dbPass)
{
parent::__construct($dsn, $dbUser, $dbPass);
}
You also have to add use Cereal\Database; in top of Cereal.php
and use PDO; in top of Database.php

Try following:
if(!$configObj){
$this->configObj = $configObj;
} else {
}
should it not be if($configObj) ?

Related

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

PHP not showing anything

I cannot see anything when on my xampp server and displays an empty page. I am trying to find the error but failed. anyone can help would be appreciated
here is class.db.php
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'db'; //name of your database
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
and index.php has at the top above <!doctype
<?PHP
include('db.class.php');
$bdd = new db();
?>
along my html code
You just created an instance of this class, this only triggered the constructor, you did not make any calls to functions, so nothing shows on that page.
For the future: enable displaying errors by adding
ini_set('display_errors',1);
this will help you to find and correct errors.

PHP Class - Use return in another function

I have one PHP Class with 2 functions DB_Connect() and LogIn(). To use LogIn() I first need to run DB_Connect and get returned value of $CONN. I do this with $this->DB_Connect(); but when I run code I'm get:
Notice: Undefined variable: CONN in
C:\XAMPP\htdocs\core\Admin.class.php on line 39
Fatal error: Call to a member function prepare() on null in
C:\XAMPP\htdocs\core\Admin.class.php on line 39
protected function DB_Connect()
{
$ROOT = dirname(__DIR__);
include $ROOT."../core/sql.php";
try {
$CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
$CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $CONN;
}
public function LogIn()
{
if($_SERVER["REQUEST_METHOD"] === "POST") {
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$this->DB_Connect();
try {
$SQL = "SELECT Password FROM Admins WHERE Username = :Username";
$SQL = $CONN->prepare($SQL);
$SQL->execute(array('Username' => $Username));
$CountRows = $SQL->rowCount();
$Result = $SQL->fetch(PDO::FETCH_ASSOC);
$PasswordCheck = $Result["Password"];
if($CountRows === "1" && password_verify($Password, $PasswordCheck)) {
$_SESSION["LoginUser"] = $Username;
$CONN = null;
header("location: home.php");
exit();
} else {
$Status = '<div class="alert alert-danger" role="alert">You have entered wrong data!</div>';
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
$CONN = null;
if(isset($Status)) {
return $Status;
}
}
$this->DB_Connect(); returns a value. It doesn't set a variable for you. You need to set a variable to its return value.
$CONN = $this->DB_Connect();

How to connect to MySQLi server

I have a login-script, but when i proceed it there com a error:
Undefined property: Users::$host in C:\wamp\www\userlogin\classes\class.database.php on line 8
There is 4 files:
<?php
session_start();
include "classes/class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$users->login($username, $password);
}
?>
<!DOCTYPE html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<form method="POST" action="" name="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
<?php
class Database
{
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno)
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
} ?>
<?php
include "class.database.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(); ?>
//dashboard
<?php echo "error"; ?>
I use localhost/index.php to run and the 3 files class.database.php and class.users.php dahsboard.php is in the directory: classes
Mybe it is a syntax-error, but i can not locate it.
I have created a database in phpmyadmin and inserted the data.
Can anybody help me?
You can't use $this for local variable, they will need to be property of the class, and you need a public one for the connection, like this:
<?php
class Database {
public $mysqli;
private $host = 'localhost';
private $user = 'root';
private $pass = 'password';
private $name = 'usersystem';
public function __construct() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $this->mysqli->connect_errno . ") ";
}else{
echo $this->mysqli->host_info . "\n";
}
}
}
?>
Other thing I notice is you don't start a session before setting it.
You should also exit after redirecting
if($stmt->fetch()) {
session_start();
$_SESSION['username'] == $username;
header("Location: dashboard.php");
exit;
}
Try changing your database connection to this:
class Database
{
// Since you are calling this variable in other methods
// you need to make it available.
public $mysqli;
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($host, $user, $pass, $name);
// You are mixing local with class-wide variables. Should all conform.
if ($this->mysqli->connect_errno)
echo "Failed to connect to MySQL: (".$this->mysqli->connect_errno.")".$this->mysqli->connect_error;
echo $this->mysqli->host_info."\n";
}
}
in the __construct method for Database change $user to $this->user, $host to $this->host etc..

Correct use of PDO procedure not using global

I am having a play around with PDO and currently have the following code but I am getting Call to a member function prepare() on a non-object and I don't want to use global.
Do I use a class or do I pass it as a variable?
Config.php
function connection()
{
try
{
$host = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
$dbConnection = new PDO("mysql:host=" . $host . ";dbname=" . $dbname.";", $dbuser, $dbpass);
return $dbConnection;
} catch (PDOException $error)
{
echo $error->getMessage();
return FALSE;
}
}
Functions.php
<?php
include('config.php');
$db = connection();
function listCars()
{
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars());
?>
You have to load the db variable into your function, in Functions.php, look at this:
Functions.php
include('config.php');
$db = connection();
function listCars($db){
$query = $db->prepare("SELECT `id` `rego` `engineSize` `type` `colour` `year` `additionalFeatures` FROM `cars`");
$result = $query->fetchAll();
return $result;
}
?>
Index.php
<?php
include('assets/misc/functions.php');
var_dump(listcars($db));
?>
However, if you're looking for a more OOP approach, try the following:
<?php
class Cars {
protected $db;
public function __construct(PDO $db){
$this->db = $db;
}
public function listCars(){
$query = $this->db->prepare("... query ...")->execute();
return $query->fetchAll();
}
}
include('config.php');
$cars = new Cars(connection());
try {
var_dump($cars->listCars());
} catch (PDOException $e) {
echo $e;
}
?>

Categories