error when close connection using mysqli on PHP - php

I am new in PHP development, I get a warning like this when making email confirmation registration:
Registration success, please login using your data
Warning: mysqli::close(): Couldn't fetch
mysqli in
/Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php on
line 42
here is the simplified code of access.php
class access {
public $host = null;
public $username = null;
public $password = null;
public $dbname = null;
public $conn = null;
public $result = null;
function __construct($xhost,$xusername,$xpassword,$xdbname) {
$this->host = $xhost;
$this->username = $xusername;
$this->password = $xpassword;
$this->dbname = $xdbname;
}
// connection to database
function connect() {
$this->conn = new mysqli($this->host,$this->username,$this->password,$this->dbname);
if (mysqli_connect_errno()) {
echo "Connection to database failed: ".mysqli_connect_error();
}
// support all languages
$this->conn->set_charset("utf8");
}
public function disconnect() {
if ($this->conn != null) {
$this->conn->close();
}
}
//saving token to the database
function saveTokens ($table, $id, $token) {
$query = "INSERT INTO $table SET id=?, token=?";
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
$statement-> bind_param('is',$id,$token);
$returnValue = $statement ->execute();
return $returnValue;
}
// get userID from given Token
function getIDFromToken($table,$token) {
$returnValue = [];
$query = "SELECT id FROM $table WHERE token='$token'";
$result = $this->conn->query($query);
if ($result != null && (mysqli_num_rows($result)>0)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
function updateEmailConfirmationStatus($status,$id) {
$query = "UPDATE users SET emailConfirmed =? WHERE id=?";
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
$statement-> bind_param('ii',$status,$id);
$returnValue = $statement ->execute();
return $returnValue;
}
// delete token when ID is available
function deleteToken($table,$token) {
$query = "DELETE FROM $table WHERE token =?";
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
$statement-> bind_param('s',$token);
$returnValue = $statement ->execute();
return $returnValue;
}
}
and I use access.php in confirmationlink.php
here is the code on confirmationlink.php
<?php
require_once("../security/access.php");
if (empty($_GET["token"])) {
echo "Please follow as per the procedure";
return;
}
$token = htmlentities($_GET["token"]);
// making connection to the database
$file = parse_ini_file("../../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
// get ID from database as per the Token created
$info = $access->GetIDFromToken("emailTokens",$token);
$id = $info["id"];
// change emailConfirmed status to 1 if user has pressed confirmation link
$result = $access -> updateEmailConfirmationStatus(1,$id);
// menghapus token apabila ID sudah terkonfirmasi ada di database
if ($result) {
$access ->deleteToken("emailTokens",$token);
echo "Registration success, please login using your data";
}
// close the connection
$access -> disconnect();
I get the error only on the last line of confirmationlink.php file. the database has been changed successfully on MySQL as I want. I also use disconnect method on other PHP file but i have no issue. but somehow I got the issue now
what went wrong in here ? Thanks in advance :)

You need to close your statements before you return the result in each of the functions:
$statement->close();

Related

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...
}
}

Register user PHP

I am trying to create a PHP script to register users. It connects my xCode with a mySQL database.
I am getting the following error:
8ee52684907bd42381d94f74f3c4d321b17c5285 Notice: Trying to get
property of non-object in
/Applications/XAMPP/xamppfiles/htdocs/SwiftAppAndMYSQL/db/MySQLDAO.php
on line 76
Fatal error: Uncaught exception 'Exception' in
/Applications/XAMPP/xamppfiles/htdocs/SwiftAppAndMYSQL/db/MySQLDAO.php:76
Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/SwiftAppAndMYSQL/scripts/registerUser.php(63):
MySQLDAO->registerUser('email', 'gui', 'Maia', '8ee52684907bd42...',
'\x99\x99S'eXqs\xE0\xC4\x80[\xB1\x07y...') #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/SwiftAppAndMYSQL/db/MySQLDAO.php
on line 76
This is my registerUser script
<?php
require ("../db/MySQLDAO.php");
require ("../db/Conn.php");
$returnValue = array();
if (
empty($_REQUEST["userEmail"]) ||
empty($_REQUEST["userPassword"]) ||
empty($_REQUEST["userFirstName"]) ||
empty($_REQUEST["userLastName"])) {
$returnValue["status"] = "400";
$returnValue["message"] = "Missing required information";
echo json_encode($returnValue);
return;
}
$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);
$salt = openssl_random_pseudo_bytes(16);
$secure_password = sha1($userPassword . $salt);
echo $secure_password;
$dao = new MySQLDAO(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass, Conn::$dbname);
$dao->openConnection();
$userDetails = $dao->getUserDetails($userEmail);
if(!empty($userDetails))
{
$returnValue["status"] = "400";
$returnValue["message"] = "Please choose different email address";
echo json_encode($returnValue);
return;
}
$result = $dao->registerUser($userEmail, $userFirstName, $userLastName, $secure_password, $salt);
if ($result) {
$userDetails = $dao->getUserDetails($userEmail);
$returnValue["status"] = "200";
$returnValue["message"] = "Sucessfully registered new user";
$returnValue["userId"] = $userDetails["user_id"];
$returnValue["userFirstName"] = $userDetails["first_name"];
$returnValue["userLastName"] = $userDetails["last_name"];
$returnValue["userEmail"] = $userDetails["email"];
} else {
$returnValue["status"] = "400";
$returnValue["message"] = "Could not register user with provided information";
}
$dao->closeConnection();
echo json_encode($returnValue);
?>
My DAO object goes bellow:
<?php
class MySQLDAO {
private $dbpassword;
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpassword;
$this->dbname = $dbname;
}
public function openConnection() {
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_error())
throw new Exception("Could not stabilish connection with database");
$this->conn->set_charset("utf8");
}
public function closeConnection() {
if ($this->conn != null)
$this->conn->close();
}
public function getUserDetails($email){
$returnValue = array();
$sql = "select * from users where 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 registerUser($email, $first_name, $last_name, $password, $salt) {
$sql = "insert unto users set email=?, first_name=?, last_name=?, user_password=?, salt=?";
$statement = $this->conn->prepare($sql);
if (!$statement){
throw new Exception($statement->error);
}
$statement->bind_param("sssss", $email, $first_name, $last_name, $password, $salt);
$returnValue = $statement->execute();
return $returnValue;
}
}
My connection class
<?php
class Conn {
public static $dbhost = "localhost";
public static $dbuser = "root";
public static $dbpass = "";
public static $dbname = "SwiftApp";
}
?>
There is one possible error I can spot:
This SQL query has a typo, it should be into, not unto, resulting in a syntax error:
$sql = "insert unto users set email=?, first_name=?, last_name=?, user_password=?, salt=?";
$statement = $this->conn->prepare($sql);
The syntax error results in $mysqli->prepare() returning false.
If this is the case the next block can't work.
if (!$statement){
throw new Exception($statement->error);
}
If $statement is false, it isn't an object, so $statement->error doesn't work and the error Trying to get property of non-object is thrown.
This should report the desired result:
/// corrected query
$sql = "insert into users set email=?, first_name=?, last_name=?, user_password=?, salt=?";
$statement = $this->conn->prepare($sql);
if (!$statement){
/// corrected error reporting
throw new Exception($this->conn->error);
}

Fatal error: Using $this when not in object context in C:\xampp\htdocs\BaseballTuts\include\class.user.php [duplicate]

This question already has answers here:
PHP $this when not in object context for set public variable from out of class
(3 answers)
Closed 8 years ago.
I'd got a problem when i'm checking if username is available in the table.
In my class.user.php I've got this error:
* Fatal error: Using $this when not in object context in C:\xampp\htdocs\BaseballTuts\include\class.user.php on line 47 *
this how my class.user.php was written:
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for registration process ***/
public function reg_user($name,$nickname,$gender,$birthdate,$address,$email,$short_info,$username,$password){
$password = md5($password);
$sql="SELECT * FROM `user` WHERE `username`='$username' OR `email`='$email'";
//checking if the username or email is available in db
$check = $this->db->query($sql) ;
$count_row = $check->num_rows;
//if the username is not in db then insert to the table
if ($count_row == 0){
$sql1="INSERT INTO `user` SET `name`='$name', `nickname`='$nickname', `gender`='$gender', `birthdate`= '$birthdate', `address`='$address', `email` = '$email', `short_info`= '$short_info', `username` = '$username', `password` = '$password'";
$result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
return $result;
}
else { return false;}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT `user_id` from `user` WHERE `email`='$emailusername' or `username`='$emailusername' and `password`='$password'";
//checking if the username is available in the table
*** $result = mysqli_query($this->db,$sql2);***
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
$_SESSION['login'] = true;
$_SESSION['id'] = $user_data['user_id'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql3="SELECT fullname FROM users WHERE uid = $uid";
$result = mysqli_query($this->db,$sql3);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'];
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
and this how i call check_login:
session_start();
include_once 'include/class.user.php';
$user = new User();
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if ($login) {
// Registration Success
header("location:home.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}
}
Call the function like the code below:
$emailusername = '';
$password = '';
$userObj = new User();
$result = $userObj->check_login($emailusername, $password);
If you still have a problem, I would suggest that you modify your code like the one below:
<?php
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if($db_connect){
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
}
/*** for registration process ***/
public function reg_user($name,$nickname,$gender,$birthdate,$address,$email,$short_info,$username,$password){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$password = md5($password);
$sql="SELECT * FROM `user` WHERE `username`='$username' OR `email`='$email'";
//checking if the username or email is available in db
$check = $this->db->query($sql) ;
$count_row = $check->num_rows;
//if the username is not in db then insert to the table
if ($count_row == 0){
$sql1="INSERT INTO `user` SET `name`='$name', `nickname`='$nickname', `gender`='$gender', `birthdate`= '$birthdate', `address`='$address', `email` = '$email', `short_info`= '$short_info', `username` = '$username', `password` = '$password'";
$result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
return $result;
}
else { return false;}
mysqli_close($db);
$this->db = null;
}
/*** for login process ***/
public function check_login($emailusername, $password){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$password = md5($password);
$sql2="SELECT `user_id` from `user` WHERE `email`='$emailusername' or `username`='$emailusername' and `password`='$password'";
//checking if the username is available in the table
*** $result = mysqli_query($this->db,$sql2);***
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
$_SESSION['login'] = true;
$_SESSION['id'] = $user_data['user_id'];
return true;
}
else{
return false;
}
mysqli_close($db);
$this->db = null;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// Get the MySQLi object
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
$sql3="SELECT fullname FROM users WHERE uid = $uid";
$result = mysqli_query($this->db,$sql3);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'];
mysqli_close($db);
$this->db = null;
}
/*** starting the session ***/
public function get_session(){
if(session_id() == '') session_start();
return $_SESSION['login'];
}
public function user_logout() {
if(session_id() == '') session_start();
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
First of all, it's better to have private $db, because you're only using this property inside the PHP Class.
Second of all, to avoid having an empty object, you need to check if this object is empty and if it is, you need to connect to the DB and fill that object. Also, you need to close the MySQL connection when you're done and you need to empty the variable.
EDIT 2:
I fixed a small issue in the PHP Session code, because it might throw an error if the Session isn't started.
I also added a flag in the __construct function so that you can call the object without connection to the DB, because the last 2 functions don't need a db call.

Mysqli oop method call

I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it
Database Class.php is below:
Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;
public function connect($host, $user, $pass, $db){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
$this->con = mysqli_connect($this->host, $this->user, $this->pass);
if(mysqli_connect_errno()){
echo "Connection Failed %s\n!", mysqli_connect_error();
exit();
}
}
public function select($condition){
$query = "select os_user from users WHERE os_user = {$condition}";
$result = mysqli_query($this->con,$query);
return $result;
}
}
this is how did I implement it:
require 'templates/dbclass.php';
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
echo $username;
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo $row->os_id;
}
}
}
But it does not show any results. When I var_dump($result) I get bool(false).
I've enabled error reporting, but there is no errors displayed.
There are 3 issues with your select function
is is vulnerable to SQL injection
it does no error checking
it is useless
Here is how it have to be
public function query($sql, $bind)
{
$db = $this->con;
$stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
$types = str_repeat("s", count($values));
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute() or trigger_error($db->error." [$sql]");
$stm->store_result();
return $stm->get_result();
}
used like this
$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
echo $row->os_id;
}

Categories