mysqli Object Oriented Programming - php

I'm trying to make my login homepage work. At the first I built my query with mysql but I always got the error "query is empty" so I decided to change over to mysqli. I'm now getting the error "Warning: mysqli_query() expects at least 2 parameters".
how can I call the first parameter "$db" in my "mysqli_query($db, $string)" from the method "connect()" in the class "database2" to make it work?
I tried with " $result = $this->cxn->query($query)" but then i got the error "Fatal error: Call to undefined method Database2::query()
<?php
class Login
{
private $username;
private $password;
private $cxn; // Database object.
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(){
include 'models/database2.php';
$vars = "include/vars.php";
$this->cxn = new Database2($vars);
}
private function getData(){
$query ="SELECT 'username', 'password' FROM 'users' WHERE 'username' = '$this->username'
AND 'password' = '$this->password'";
$result = mysqli_query($query) or die(mysql_error());
$num_row = mysqli_num_rows($result);
if ($num_row>1) {
return TRUE;
}else{
throw new Exception("The query was not successful!");
}
}
function close(){
$this->cxn->close_connect();
}
}
?>
Database2 class:
<?php
class Database2{
private $host;
private $user;
private $password;
private $database;
function __construct($filename){
if(is_file($filename)){
include $filename;
}else{
throw new Exception("Error Processing Request");
}
$this->host = $host;
$this->user = $user;
$this->password =$password;
$this->database =$database;
$this->connect();
}
public function connect(){
// connect to the server.
$db = new mysqli($this->host, $this->user, $this->password);
if ($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";
}
}
public function close_connect(){
mysql_close();
}
}
?>
i appreciate any help

If you use procedural style, you have to set and use a "$db" variable in the database2 class.
Set the variable in the connect function:
$this->db = new mysqli($this->host, $this->user, $this->password);
And then, you can use the $db in the database2 object
$result = mysqli_query($this->cxn->db, $query);

Related

I don't know the right way to connect to my db in my login model, i'm using (oop - mysqli)

i'm learning oop , i have those tow errors (mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\oop2\model\login.php on line 38 , : mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\oop2\model\login.php on line 40) and i don't know how the wright way to connect to my db in oop and mysqli.
database connect
database connect
class Database
{
private $host;
private $user;
private $password;
private $database;
function __construct($filename)
{
if(is_file($filename)) include $filename;
else throw new Exception("Error!");
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
}
public function connect()
{
// connect to the server
if(!mysqli_connect($this->host,$this->user, $this->password,$this->database))
throw new Exception("Error: not connected to the server.");
}
function close()
{
mysql_close();
}
}
login model
class Login{
private $username;
private $password;
private $cxn;
public function __construct($username,$password)
{
$this->setData($username,$password);
$this->connectToDb();
$this->getData();
}
private function setData($username,$password)
{
$this->username = $username;
$this->password = $password;
}
private function connectToDb()
{
include '../model/database.php';
$config = "../model/config.php";
$this->cxn = new Database($config);
$this->cxn->connect();
}
public function getData()
{
$query = "SELECT * FROM admin
WHERE
'username' = '$this->username'
AND
'password' = '$this->password'
";
$sql = mysqli_query($this->cxn->connect(),$query);
if (mysqli_num_rows($sql) > 0)
{
return TRUE;
}
else
{
throw new Exception("Error Processing Request");
}
}
public function close()
{
$this->cxn->close();
}
}
mysqli_connect returns a link object representing the connection to the MySQL server. In your Database class you must save the return value of mysqli_connect:
class Database {
private $host;
private $user;
private $password;
private $database;
private $connection; //Add this
Then:
public function connect() {
if(!$this->connection) {
// connect to the server
$this->connection = mysqli_connect($this->host,$this->user, $this->password,$this->database);
//Do some error checking here !
}
return $this->connection;
}
You must pass $host, $user, $password and $database to DataBase class like this.
class Login{
private $username;
private $password;
private $cxn;
public function __construct($username,$password)
{
$this->setData($username,$password);
$this->connectToDb();
$this->getData();
}
private function setData($username,$password)
{
$this->username = $username;
$this->password = $password;
}
private function connectToDb()
{
include '../model/database.php';
$config = "../model/config.php";
$this->cxn = new Database($config, $host, $user, $password, $database);
$this->cxn->connect();
}
public function getData()
{
$query = "SELECT * FROM admin
WHERE
'username' = '$this->username'
AND
'password' = '$this->password'
";
$sql = mysqli_query($this->cxn->connect(),$query);
if (mysqli_num_rows($sql) > 0)
{
return TRUE;
}
else
{
throw new Exception("Error Processing Request");
}
}
public function close()
{
$this->cxn->close();
}
}
And change your Database class with this
class Database
{
private $host;
private $user;
private $password;
private $database;
function __construct($filename, $host, $user, $password, $database)
{
if(is_file($filename)) include $filename;
else throw new Exception("Error!");
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
}
public function connect()
{
// connect to the server
if(!mysqli_connect($this->host,$this->user, $this->password,$this->database))
throw new Exception("Error: not connected to the server.");
}
function close()
{
mysql_close();
}
}

how to change mysql_connect() to PDO

This is my db connect class which is working with php5.3 but it not working after i updated the php5.4 and show error that it's expired.
class DB {
function DB() {
$this->host = "localhost";
$this->db = "dbtest";
$this->user = "root" ;
$this->pass = "password";
$this->link = mysql_connect($this->host, $this->user, $this->pass) or die("<br>Could not connect 1: " . mysql_error());
mysql_select_db($this->db);
}
function query($query) {
$result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
return $result;
}
function thislink() {
return $this->link;
}
function close() {
mysql_close($this->link);
}
}
How to change it into PDO or mysqli so the wamp could use it
You can't.
Your class is not a black box, you have for example a public method that returns the MySQL link identifier:
function thislink() {
return $this->link;
}
If you change that to another database interface, you will run into problems when you call this method as it will not contain what the calling end is expecting.
The same applies to your public query() method:
function query($query) {
$result = mysql_query($query, $this->link) or die ("<br>Could not execute command 1: ".mysql_error());
return $result;
}
That returns a mysql resource in case of for example a SELECT statement so if you change that to msyqli or PDO, the calling side will not be able to handle it.
class DB {
function DB() {
$this->host = "localhost";
$this->db = "dbtest";
$this->user = "root" ;
$this->pass = "password";
$this->link = new PDO("mysql:host=$this->host;dbname=$this->db", $this->user, $this->pass);
}
function query($query) {
$result = $this->link->query($query);
return $result;
}
function thislink() {
return $this->link;
}
function close() {
$this->link = NULL;
}
}
Your class should look something like this:
Note that I change the constructor to __construct(), since in PHP 7 the other way what you used will be deprecated. Also I put the variables as arguments in the constructor with default values. I also enabled error mode for your PDO connection, only have it on in testing!, never in production.
<?php
class DB {
public $host;
public $db;
public $user;
public $pass;
private $link;
public function __construct($host = "localhost", $db = "dbtest", $user = "root", $pass = "password") {
$this->host = $host;
$this->db = $db;
$this->user = $user;
$this->pass = $pass;
try {
$this->link = new PDO("mysql:host={$this->host};dbname={$this->db}", $this->user, $this->pass);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOExcpetion $e) {
echo $e->getMessage();
}
}
function query($query) {
$stmt = $this->link->prepare($query);
$stmt->execute();
return $stmt;
}
function thislink() {
return $this->link;
}
function close() {
$this->link = null;
}
}
?>
For more information about PDO see the manual: http://php.net/manual/en/book.pdo.php
You may also want to take a look into prepared statements.

OOP using php and mysqli to return data from database

I have a Database php file and a user php file. The Database is where I make my connection to the database.
<?php
/*
* Mysqli database class - only one connection
*/
class Database{
private $_connection;
private static $_instance; //The single instance
private $_host = 'localhost';
private $_username = 'root';
private $_password = '';
private $_database = 'blogwebsite';
public static function getInstance(){
if(!self::$_instance){ // If no instance make one
self::$_instance = new self();
}
return self::$_instance;
}
/*
* Constructor
*/
public function __construct(){
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()){
trigger_error("Failed to connect to MySQL: " .
mysqli_connect_errno(), E_USER_ERROR);
}else{
echo "You are connected to " . $this->_database;
}
}
// Magic method clone is empty to prevent duplication of connection
public function __clone(){ }
// Get mysqli connection
public function getConnection(){
return $this->_connection;
}
}
?>
This is the user page and I am including the Database page. I get an error that is saying ' Undefined variable: mysqli' AND 'Call to a member function prepare() on a non-object'.
<?php
include('class.database.php');
class api{
public function __construct(){
$db = Database::getInstance();
$mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username);
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
$username = new api();
echo $username->getUsername($username);
?>
Can anyone please help with any assistance. Thank you verry much.
You don't have a 'mysqli' variable in class 'api'. Also, you should call getConnection() after getting the Database instance.
class api{
private $mysqli;
public function __construct(){
$db = Database::getInstance()->getConnection();
$this->mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $this->mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username);
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
You need to create a local variable $mysql :
class api{
protected $mysql; // <-- Here
public function __construct(){
$db = Database::getInstance();
$this->mysqli = $db->getConnection();
}
public function getUsername($username){
$statement = $this->mysqli->prepare("SELECT username FROM users");
$statement->bind_param('s', $username); // <-- what this for ?
$statement->execute();
$statement->bind_result($username);
$statement->fetch();
$statement->close();
return $username;
}
}
$username = new api();
echo $username->getUsername($username);

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.

QLSTATE[HY000] [1045] Access denied for user

Anyone know what this means? not a very experience programmer.
SQLSTATE[HY000] [1045] Access denied for user ''#'..*.' (using password: NO)SELECT * FROM **_Students
code in StudentDataSet
require_once ('Models/StudentData.php');
require_once ('Models/Database.php');
class StudentsDataSet {
protected $_dbHandle, $_dbInstance;
public function __construct()
{
$this-> _dbInstance = Database::getInstance();
$this-> _dbHandle = $this-> _dbInstance-> getdbConnection();
}
public function fetchAllStudents() {
$sqlQuery = 'SELECT * FROM MUD193_Students'; // put your students table name
echo $sqlQuery; //helpful for debugging to see what SQL query has been created
$statement = $this->_dbHandle->prepare($sqlQuery); // prepare PDO statement
$statement->execute(); // execute the PDO statement
$dataSet = [];
while ($row = $statement->fetch()) {
$dataSet[] = new StudentData($row); }
return $dataSet; }
Code in StudentData
<?php
class StudentDataClass {
private $_id, $_firstName, $_lastName, $_international, $_courseID;
public function __construct($dbRow) {
$this->_id = $dbRow['id'];
$this->_firstName = $dbRow['first_name'];
$this->_lastName = $dbRow['last_name'];
if ($dbRow['international'])
$this->_international = 'yes';
else
$this->_international = 'no'; $this->_courseID = $dbRow['courseID'];
}
public function getStudentID() {
return $this->_id;
}
}
Code in Databse
<?php
class Database {
protected static $_dbInstance = null;
protected $_dbHandle;
public static function getInstance() {
$username = '****';
$password = '****';
$host = '*******';
$dbName = '****';
if (self::$_dbInstance === null) {
self::$_dbInstance = new self($username, $password, $host, $dbName);
}
return self::$_dbInstance;
}
private function __construct($username, $password, $host, $database) {
try {
$this->_dbHandle = new PDO("mysql:host=$host; dbname=
$database; $username, $password");
} // creates database handle with connection info
catch (PDOException $e) { // catch any failure to connect to database
echo $e->getMessage();
}
}
public function getdbConnection() {
return $this->_dbHandle; // returns the database handle to be used elsewhere
}
public function __destruct() {
$this->_dbHandle = null; // destroys the destroys the database handle
}
}
This is a Access denied error. You should check your database username and password with which you login
Define your;
Database Name
Database Username
Database User Password
Probably script could not reach variables that you defined.
If you give more information like which language you are using to connect database, we can help you better.

Categories