PHP Class - Use return in another function - php

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();

Related

Connection is not defined

I have the following code
<?php
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function getIPforBDD(){
return $_SERVER['REMOTE_ADDR'];
}
function UpdateUserProfile()
{
$requete = "SELECT * FROM users WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
if($resultat->rowCount() == 0)
exit();
foreach($result as $ligne)
{
$userIP = $ligne['ip'];
$userhasFinish = $ligne['finish'];
$userLastPage = $ligne['lastPage'];
}
}
function CheckUserPosition()
{
UpdateUserProfile();
if(!$userExist)
AddUser();
return GetUserStatus();
}
function GetUserStatus()
{
$page;
if($userHasFinish)
$page = "end.php";
else
$page = $userLastPage;
return $page;
}
function AddUser()
{
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
function SavePageInBDD($page){
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}
?>
But, I have a problem when I use it
( ! ) Notice: Undefined variable: dbh in C:\wamp64\www\HawkI\bdd.php
on line 66
I do not understand correctly how PHP work it's the first time I use it, but I tried to make
global $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
That doesn't work too.
Also, it seems that value that are put outside of functions are not global like it would be in js, how can I make something accessible from everywhere (like file that include that file)
Thanks
Better way would be to do something like this:
function getDB(){
$dbh = null;
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
And than in your functions do this:
function AddUser()
{
$dbh = getDB();
if(!is_null($dbh)){
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
}
To use $dbh inside a function, you need to include global keyword inside the function scope.
You can find the global keyword explanation here http://php.net/manual/en/language.variables.scope.php#language.variables.scope.global
function AddUser()
{
global $dbh;
$requete = "INSERT INTO users (ip, finish, lastPage) VALUES (".getIPforBDD().", ".false.", questionnaire_initial.php)";
$result = $dbh->query($requete);
}
You may use like this
$host = "localhost";
$dbname = "hawkI";
$user = "root";
$password = "";
$userExist = false;
$userIP = null;
$userHasFinish = null;
$userLastPage = null;
$dbh = NULL;
function db () {
try {
if ($GLOBALS['dbh']===NULL){
$GLOBALS['dbh'] = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
}
return $GLOBALS['dbh'];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function SavePageInBDD($page){
$dbh = db();
$requete = "UPDATE users SET lastPage = '.$page.' WHERE ip = ".getIPforBDD();
$result = $dbh->query($requete);
}

PDO lastInsertId returns 0

I keep getting 0 in PDO lastInsertId. Here are my codes:
public static function createNewUser($email){
$password = self::rand_string(6);
$username = explode("#", $email);
$username = $username[0];
$passwordhashed = password_hash($password. self::salt(), PASSWORD_DEFAULT);
$register = self::connect()->prepare("INSERT INTO `user`(email,username,password,password_salt,type)VALUES(?,?,?,?,?)");
$register->execute(array($email,$username,$passwordhashed,$password,'customer'));
$user_id = self::pdolastid();
if($register){
return $user_id;
}
else{
return false;
}
}
and the last insert id function is:
public static function pdolastid(){
$last = self::connect()->lastInsertId();
return $last;
}
I have tried both with the pdolastid function and with self::connect()->lastInsertId().
The connect function is:
public static function connect(){
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new \PDO("mysql:host=$servername;dbname=pw;port=3306;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $conn;
}
catch(PDOException $e)
{
$con_error = "Connection failed: " . $e->getMessage();
return $con_error;
}
}
The database has id as the primary key and is auto-increment
Someone please help

Issue with simple SQL statement / PHP function not working

I have a simple function to write into my database. This is the error I am getting.
This is the error I am getting
Notice: Trying to get property of non-object in /var/sites/q/quasisquest.uk/public_html/KeepScore/MySQLDao.php on line 92 Fatal error: Uncaught exception 'Exception' in /var/sites/q/quasisquest.uk/public_html/KeepScore/MySQLDao.php:92 Stack trace: #0 /var/sites/q/quasisquest.uk/public_html/KeepScore/createCommunity.php(26): MySQLDao->createCommunity('radowns82#gmail...', 'YGHFYG', 'Endcliffe') #1 {main} thrown in /var/sites/q/quasisquest.uk/public_html/KeepScore/MySQLDao.php on line 92
This is the initial PHP script that calls it:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$code = htmlentities($_POST["code"]);
$communityname = htmlentities($_POST["communityname"]);
$dao = new MySQLDao();
$dao -> openConnection();
$result = $dao -> createCommunity($email, $code, $communityname);
$dao->closeConnection();
?>
This is MySQLDao.php
<?php
class MySQLDao{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
public function __construct(){
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
public function openConnection()
{
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno())
echo new Exception("Could not establish connection with database");
}
public function getConnection()
{
echo ("2");
return $this->conn;
}
public function closeConnection()
{
if($this->conn!=null)
$this->conn->close();
}
public function getUserDetails($email)
{
$returnValue = array();
$sql = "select * from users where user_email='".$email."'";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
return $returnValue;
}
public function getUserDetailsWithPassword($email, $userPassword)
{
$returnValue = array();
$sql = "select id, user_email, user_name from users where user_email = '".$email."' and user_password = '".$userPassword."'";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1 )){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
return $returnValue;
}
public function registerUser($email, $password, $username)
{
$sql = "insert into users set user_email=?,user_password=?,user_name=?";
$statement = $this->conn->prepare($sql);
if(!$statement)
throw new Exception($statement->error);
$statement->bind_param("sss", $email, $password, $username);
$returnValue = $statement->execute();
return $returnValue;
}
public function createCommunity($email, $code, $communityname)
{
$sql = "insert into communities set email=?,code=?,communityname=?";
$statement = $this->conn->prepare($sql);
if(!$statement){
throw new Exception($statement->error);
}
$statement->bind_param("sss", $email, $code, $communityname);
$returnValue = $statement->execute();
return $returnValue;
}
}
?>
That 'communities' table also has an 'id' column (1st column) which I am not posting to as I thought it would auto-populate and increment... maybe this is where I am going wrong?
If the connection fails first you need to know why so show the actual database error. and second, there is very little point in continuing the scripts execution without a connection to the database.
So can I suggest this change to your openConnection() method
Also if you think there is any chance of something wrong in the MSYQLI code these 4 lines will basically ensure you get told about any errors, while you are developing, specially if you are developing on a live server with ERROR REPORTING turned off.
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
public function openConnection()
{
$this->conn = new mysqli($this->dbhost, $this->dbuser,
$this->dbpass, $this->dbname
);
if ($mysqli->connect_error) {
echo 'Connect Error: ' . $mysqli->connect_errno . ' - '
. $mysqli->connect_error;
exit;
}
}

PHP & SQL : Throws fatal error when $_Request are filled

I just started learning, but why is it that when I don't fill the info in the URL it connects to the database, but when I fill it in it gives a fatal error?
Ex. when I type
http://ehlien.com/php/signup.php?firstname=Mohamed&lastname=Mohamed&username=alpha&email=mohamed.mohd#hotmail.com&password=mohamed
It throws:
Fatal error: Uncaught exception 'Exception' with message 'Failed to connect to database' in /home/torokage/public_html/php/classes/DB.class.php:22 Stack trace: #0 /home/torokage/public_html/php/signup.php(35): DB->connect() #1 {main} thrown in /home/torokage/public_html/php/classes/DB.class.php on line 22
But when I type
http://ehlien.com/php/signup.php
It gives me my error I set up:
{"status":"400","message":"Please fill in the missing information..."}
I don't have a lot of knowledge on php and mysql, just trying to figure it out on my own and through some tutorials but I can't get this to work to continue...
CODE, signup.php:
<?php
require('classes/User.class.php');
require('classes/DB.class.php');
require('classes/Connection.class.php');
$firstname = null;
$lastname = null;
$username = null;
$email = null;
$password = null;
$repassword = null;
if (empty($_REQUEST["firstname"]) ||
empty($_REQUEST["lastname"]) ||
empty($_REQUEST["username"]) ||
empty($_REQUEST["email"]) ||
empty($_REQUEST["password"]))
{
$returnError["status"] = "400";
$returnError["message"] = "Please fill in the missing information...";
echo json_encode($returnError);
return;
}
$firstname = htmlentities($_REQUEST["firstname"]);
$lastname = htmlentities($_REQUEST["lastname"]);
$username = htmlentities($_REQUEST["username"]);
$email = htmlentities($_REQUEST["email"]);
$password = md5(htmlentities($_REQUEST["password"]));
$DB = new DB(Connection::$db_host, Connection::$db_name, Connection::$db_user, Connection::$db_pass);
$DB->connect();
$checkUsername = $DB->checkIfUsernameExists($username);
if (!empty($checkUsername))
{
$returnError["status"] = "400";
$returnError["message"] = "That username has already been taken. Please try again...";
echo json_encode($returnError);
return;
}
$checkEmail = $DB->checkIfEmailExists($email);
if (!empty($checkEmail))
{
$returnError["status"] = "400";
$returnError["message"] = "That email has already been taken. Please try again...";
echo json_encode($returnError);
return;
}
$signUpUser = $DB->signUpUser($firstname, $lastname, $username, $email, $password);
if ($signUpUser)
{
$userDetails = $DB->getUserDetails($username);
$user["status"] = "200";
$user["message"] = "Success! You have now been registered.";
$user["ID"] = $userDetails["ID"];
$user["firstname"] = $userDetails["firstname"];
$user["lastname"] = $userDetails["lastname"];
$user["username"] = $userDetails["username"];
$user["email"] = $userDetails["email"];
}
else
{
$user["status"] = "400";
$user["message"] = "Sorry, this account has already been taken. Please try again...";
}
$DB->disconnect();
echo json_encode($user);
?>
DB.class.php
<?php
class DB {
protected $db_host = null;
protected $db_name = null;
protected $db_user = null;
protected $db_pass = null;
protected $db_conn = null;
protected $db_resu = null;
// Constructor
function __construct($db_host, $db_name, $db_user, $db_pass) {
$this->db_host = $db_host;
$this->db_name = $db_name;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
}
// Connect to database
public function connect() {
$this->db_conn = new MySQLi($this->db_host, $this->db_name, $this->db_user, $this->db_pass);
if (mysqli_connect_errno())
throw new Exception("Failed to connect to database");
$this->db_conn->set_charset("utf8");
}
// Disconnect from database
public function disconnect() {
if ($this->db_conn != null)
$this->db_conn->close();
}
// Check if username exists
public function checkIfUsernameExists($username) {
$result = mysql_query("SELECT USERNAME FROM USERS WHERE EMAIL = '$username'");
if(mysql_num_rows($result) == 0){
return false;
} else {
return true;
}
}
// Check if email exists
public function checkIfEmailExists($email) {
$result = mysql_query("SELECT EMAIL FROM USERS WHERE EMAIL = '$email'");
if(mysql_num_rows($result) == 0){
return false;
} else {
return true;
}
}
// Get user informationd
public function getUserDetails($username) {
$command = mysql_query("SELECT * FROM USERS WHERE USERNAME = '$username'");
$value = array();
$result = $this->db_conn->query($command);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$value = $row;
}
}
return $value;
}
// Sign up new user
public function signUpUser($firstname, $lastname, $username, $email, $password) {
$command = "INSERT INTO USERS SET FIRSTNAME=?, LASTNAME=?, USERNAME=?, EMAIL=?, PASSWORD=?";
$sql = $this->db_conn->prepare($command);
if (!$sql)
throw new Exception($sql->error);
$sql->bind_param("sssss", $firstname, $lastname, $username, $email, $password);
$value = $sql->execute();
return $value;
}
}
?>
When you didn't use any value or parameters, it's showing the error set up by you because it couldn't pass the validation step set up by you.
But when you are passing the values or parameters, it passes your validation and tries to connect with the database first as per this code of yours:
$DB = new DB(Connection::$db_host, Connection::$db_name, Connection::$db_user, Connection::$db_pass);
$DB->connect();
But it throws an exception: Failed to connect to database meaning that your database connection credentials are wrong and thus, can not connect with the database.
You may get more friendly error message by changing inside the public function connect() of DBclass to this:
// Connect to database
public function connect() {
try {
$this->db_conn = new MySQLi($this->db_host, $this->db_name, $this->db_user, $this->db_pass);
$this->db_conn->set_charset("utf8");
} catch (Exception $e ) {
echo "Failed to connect to database";
echo "Error: " . $e->message; // remove when in live...
}
}

PHP Select with PDO Call to a member function prepare() on a non-object error

I'm getting a Call to a member function prepare() on a non-object error in my PHP when using PDO to select data that was sent via an AJAX call.
Searching around on StackOverflow I've found many answers to this error, but none work to fix my problem.
The weird part is that the other PHP files use the same PDO calls and work successfully, but this one is giving me the non-object error only.
To note, the PDO connection is identical to the other pages where it works, so I know that's not causing the problem.
Also, I have tested that the AJAX data sent is being received, and that is working too.
PHP Code
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
Finally, here's the output when I var_dump() the PDO connection.
object(PDO)#1 (0) {}
For this to work, you need to use the global variable scope, explained here: http://php.net/manual/en/language.variables.scope.php
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
global $dbh, $username, $password_hash, $loggedinstatus, $pts;
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
global $dbh, $inPword, $password_hash, $loggedinstatus, $username;
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
But this can get messy very quickly.
I suggest you put the variables in an array or using OOP for a more robust solution: http://php.net/manual/en/language.oop5.php
This is how you can define it in a class..
class someClass {
private $db;
public function __construct(){
$this->dbconnect();
}
private function dbconnect() {
try { //try connection
$dbh = new PDO('mysql:host=localhost;dbname=somenane', 'usernane', 'pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh = $dbh;
} catch (Exception $e) { //connection failed
die("Oh no! It seems we took too long to respond");
}
}
public function getLoginInfo() {
$sth = $this->dbh->prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
//cont the code
}
}
Not sure if it's good enough..but it will work..

Categories