Mysqli oop method call - php

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

Related

MySQLi Prepare Statement and OOP PHP Query Returns 0 Row

Trying to get data from MySQLi using PHP OOP apporoach I am getting No rows while I am sure I have match row in the database
I have a class called db stored in a file as db.inc.php and it is like
<?PHP
class db {
private $DBSERVER;
private $DBUSERNAME;
private $DBPASSWORD;
private $DBNAME;
protected function connect(){
$this->DBSERVER = "localhost";
$this->DBUSERNAME = "root";
$this->DBPASSWORD = "";
$this->DBNAME = "maator";
$conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
?>
I have an extended class called SetData in SetData.inc.php which like
<?PHP
include_once('db.inc.php');
class SetData extends db {
private $page;
private $region;
private $conn;
function __construct() {
$this->conn = new db();
}
public function SetBox($vpage, $vregion){
$this->page = $vpage;
$this->region = $vregion;
$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
$stmt->bind_param("ss", $this->page, $this->region);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows === 0) exit('No rows');
$stmt->bind_result($titlerow,$descriptionrow);
$stmt->fetch();
$title = $titlerow;
$description = $descriptionrow;
$stmt->free_result();
$stmt->close();
}
}
?>
and finally in front page I have
<?PHP
$page = 'game';
$region = 'ASIA';
include '../inc/SetData.inc.php';
$cls = new SetData();
$cls->SetBox($page, $region);
I don't know what dbconnect() is, you need to call your connect() method here:
//$this->conn = new dbconnect(); // NO!
$this->conn = $this->connect();
Also, you shouldn't call connect() here, you already have a connection in $conn:
//$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?"); // NO!
$stmt = $this->conn->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
Then, what do you want to do with $title and description? Maybe return them?
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
return array('title' => $titlerow, 'description' => $descriptionrow);
Then call SetBox() and display:
$result = $cls->SetBox($page, $region);
echo $result['title'];
Or set properties:
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$this->title = $titlerow;
$this->description = $descriptionrow;
$stmt->free_result();
$stmt->close();
Then call SetBox() and display:
$cls->SetBox($page, $region);
echo $cls->title;

Call to a member function prepare() on null in crud.class.php on line 46

I don't know why I have this error, I am trying to use PDO to call a prepare method but it gives me errors
Here is my code:
public function create($user,$db){
$return_array = array("success"=>true,"message"=>"");
$create_user = new User("", "", "", "");
//validate the user
$validation = new Validation();
/*if(!$validation->username($user->getUsername())){
$return_array['success'] = false;
$return_array['message'] = $validation->get_username_criteria()."\n";
echo $return_array['message'];
}
if(!$validation->password($user->getPassword())){
$return_array['success'] = false;
$return_array['message'] = $validation->get_password_criteria()."\n";
echo $return_array['message'];
}*/
if($return_array['success']){
$insert_query = "INSERT INTO 'user' ('username', 'password', 'level')VALUES (:username, :password, :level)";
$stmt = $this->db->prepare($this->insert_query);
$stmt->bindValue(":username", $create_user->getUsername(), PDO::PARAM_STR);
$stmt->bindValue(":password", $create_user->getPassword(), PDO::PARAM_STR);
$stmt->bindValue(":level", $create_user->getLevel(), PDO::PARAM_INT);
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
echo "lalala";
return $return_array;
}
else
{
echo "lululu";
return $return_array;
}
}
here is my connection to database:
class Database{
private $DB_USER="";
private $DB_PASS="";
private $DB_NAME="";
private $DB_HOST="";
private $db;
public function _construct(){
$this->db = new PDO("mysql:host={$DB_HOST};dbname={$DB_NAME}", $DB_USER, $DB_PASS);
}
public function get_db(){
return $this->db;
}
public function _destruct(){
$this->db = null;
}
and here is where I call the method create():
$username = $_POST['username'];
$password = $_POST['password'];
$level = $_POST['level'];
$id = $_POST['id'];
$user = new User($id,$username,$password,$level);
$crud_obj = new crud();
$db_obj = new Database();
if($crud_obj->create($user,$db_obj->get_db())){
echo "Successfully registered!";
}

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

Simple mySQLi select to an array

Building from a tutorial I found online.
I m trying to select all items from the 'items' table and create an array. Not sure how this is suppose to work. This $result = $this->connection->query($q); is what is causing the problem.
<?php
//DB.class.php
class DB {
protected $db_name = 'dbname';
protected $db_user = 'user';
protected $db_pass = 'pass';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// check connection
if ($connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
make a construct function like
public $mysqli;
public function __construct()
{
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$this->mysqli = $mysqli;
}
public function sel($table,$whr)
{
$query = "SELECT * FROM ".$table." where id='$whr'";
$result = $this->mysqli->query($query);
$total = array();
while($row = $result->fetch_assoc()){
//print_r($row);die;
$total[] = $row;
}//print_r($total);die;
return $total;
}
I think you should set a constructor, but if you don't want, just return an instance of it first and set your $this->connection property instead of $connection (the normal variable):
class DB {
protected $db_name = 'test';
protected $db_user = 'test';
protected $db_pass = 'test';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// ^^ this one, not $connection
// check connection
if ($this->connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
return $this->connection; // then return this
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
// ^ so that if you call this, you have the mysqli object
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
$db = new DB(); // instantite,
$db->connect(); // then connect, shouldn't have to have this if you put the connection automatically on construct
$result = $db->sel('users'); // feed a valid existing table name
echo '<pre>';
print_r($result);

PDO query doesn't work

I can't do a query.
This is my code, where I connect to database and try to query.
EDIT :
class DatabaseConnection {
private $host;
private $port;
private $dbname;
private $username;
private $password;
private $query;
function __construct($host, $port, $dbname, $username, $password) {
$this->host = $host;
$this->port = $port;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
try {
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
function setQuery($query) {
$this->query = $query;
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
}
}
$db = new DatabaseConnection('144.76.6.45','5432','eu','eu','eu123');
$db->setQuery('SELECT * FROM user');
This is my code, I don't have any errors, but still it doesn't work.....
Depending on the type of query you will want to fetch data after executing it. Take a look at fetch() and fetchAll() methods.
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
or use a loop and fetch row by row
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}
after your edit:
Try to replace:
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
with
$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
and then call prepare method on it: $sth = $this->db->prepare($this->query); instead of $sth = $db->prepare($this->query);

Categories