PHP mysqli query: couldn't fetch mysqli - php

I am trying to make a db connection and check a table for existing data. However I recieve this error and I am unable to find the cause:
Warning: mysqli::query(): Couldn't fetch mysqli in
/usr/share/nginx/www/me/container/class_lib.php on line
33 Warning: mysql_fetch_assoc() expects
parameter 1 to be resource, null given in
/usr/share/nginx/www/me/container/class_lib.php on line
97
class dbHandler {
static $dbObj = null;
protected $db_host = 'localhost'; #db host
protected $db_username = 'user'; #db username
protected $db_password = 'password'; #db password
protected $db_name = 'db'; #db name
function __construct()
{
# connect if not connected
if(self::$dbObj === null)
{
self::$dbObj = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die($this->dbObj->error);
}
mysqli_set_charset(self::$dbObj, "utf8");
}
// query: query the db
public function query($query)
{
return self::$dbObj->query($query);
}
}
/*
class userLogin
create user login
*/
class userLogin {
private $username;
private $password;
function __construct($username, $password) {
$this->_dbConn = new dbHandler();
$this->username = $username;
$this->password = $password;
}
public function verifyCredentials() {
if($this->verifyUsername())
{
} else {
exit;
}
if($this->verifyPassword())
{
} else {
exit;
}
}
private function verifyUsername() {
if(!(preg_match('/[^a-z_\-0-9]/i', $this->username)))
{
return true;
}
}
private function verifyPassword() {
$query = "SELECT * FROM tbl_user";
$result = $this->_dbConn->query($query);
$row = mysql_fetch_assoc($result);
var_dump($row);
}
}
What am I doing wrong here?

All your wrapper is over a mysqli object oriented way, and suddenly you have this line?
$row = mysql_fetch_assoc($result);
You have to use the fetch_assoc from the mysqli result object
$result->fetch_assoc()

Your SQL query is clearly failing. Why you have a function query to call a query I don't know but I have a feeling that is the route cause of your issue. You would be better off with something like this:
class dbHandler extends mysqli {
protected $db_host = 'localhost'; #db host
protected $db_username = 'user'; #db username
protected $db_password = 'password'; #db password
protected $db_name = 'db'; #db name
function __construct()
{
parent::__construct($this->db_host, $this->db_username, $this->db_password, $this->db_name);
if($this->connect_errno)
{
trigger_error('Unable to connect to the database [' . $this->connect_errno . ']: ' . $this->connect_error, E_USER_ERROR);
}
}
public function __destruct()
{
parent::close();
}
}
/*
class userLogin
create user login
*/
class userLogin {
private $username;
private $password;
function __construct($username, $password) {
$this->_dbConn = new dbHandler();
$this->username = $username;
$this->password = $password;
}
public function verifyCredentials() {
if($this->verifyUsername())
{
} else {
exit;
}
if($this->verifyPassword())
{
} else {
exit;
}
}
private function verifyUsername() {
if(!(preg_match('/[^a-z_\-0-9]/i', $this->username)))
{
return true;
}
}
private function verifyPassword() {
$query = "SELECT * FROM tbl_user";
$result = $this->_dbConn->query($query);
if($this->_dbConn->errno)
{
trigger_error('Error fetching users from table. Query: ' . $query . '. Error: ' . $this->_dbConn->error);
return false;
}
if($result->num_rows)
{
while($row = $result->fetch_assoc())
{
var_dump($row);
}
}
}
}
Let me know how you get on with that.

So... I never gave the mysql user from localhost any grants. Only from the remote LAN. Problemo solved.

Probably you are closing the connection too early? DBConnect->close();?
so, if you try to execute any query after that, you will get an error!

Related

Problem with PHP class for MySQLi Request

i've some trouble with my Script.
I'm trying to create a login script based on classes
The mysql request is handled by the checkLogin Class.
If the request is succesfull it return the Result to the login Class (throw back to index.php with ?status=1)
My Problem is that the SQL request isn't triggered and throws back with ?status=0
I've testet the SQL in phpmyadmin and its correct.
I've testet the $this->postUser and it contains the correct value
<?php
require ("globals.php");
require ("../src/class.connect.php");
require ("../src/class.login.php");
if($_POST)
{
if(isset($_POST['submit']))
{
if(empty($_POST['user']))
{
$request = null;
}
else
{
$request = $_POST['user'];
}
$a = new login($request);
}
}
?>
--class.connect.php
<?php
class dbh
{
private $servername;
private $username;
private $Password;
private $dbname;
protected function connect()
{
$this->servername = HOST;
$this->username = USER;
$this->password = PW;
$this->dbname = DB;
$db = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
mysqli_set_charset($db, 'utf8');
return $db;
}
}
?>
--class.login.php
<?php
class checkLogin extends dbh
{
private $postUser;
protected function getlogin()
{
$this->postUser = $this->request;
$SQL = "SELECT user, isadmin, user_data, name, surname FROM `fm_user`, `fm_support` WHERE sup_id = user_data AND user = ? LIMIT 1";
$stmt = $this->connect()->prepare($SQL);
$stmt->bind_param("s", $this->postUser);
if ($stmt->execute()) {
$result = $stmt->get_result();
$getUser = $result->fetch_assoc();
$result[] = $getUser;
return $result;
}
else
{
header('location: ../index.php?status=0-'.$this->postUser); //$this->postUser - Just to check if the Value is correct given.
die();
}
}
}
class login extends checkLogin
{
protected $request;
public function __construct($request)
{
$this->request = $request;
$this->showLogin();
}
private function showLogin()
{
$data = $this->getlogin();
$cookieVal = "%".$getUser["user"]."%".$getUser["isadmin"]."%".$getUser["name"]."%".$getUser["surname"]."%";
createCookie($cookieVal);
header("location: ../index.php?status=1");
die();
}
}
?>

Unable to connect to mysql using php

While trying to connect through PHP it displays
Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'bookedscheduler' in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 52
Warning: mysqli_select_db() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 53
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 54
Cannot modify header information - headers already sent by (output started at C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php:53) in C:\wamp\www\booked\Pages\Page.php on line 138
My config.php
database connection
$conf['settings']['database']['type'] = 'mysql';
$conf['settings']['database']['user'] = 'booked_user';
$conf['settings']['database']['password'] = '';
$conf['settings']['database']['hostspec'] = '127.0.0.1';
$conf['settings']['database']['name'] = 'bookedscheduler';
Mysqlconnection.php file
class MySqlConnection implements IDbConnection
{
private $_dbUser = '';
private $_dbPassword = '';
private $_hostSpec = '';
private $_dbName = '';
private $_db = null;
private $_connected = false;
/**
* #param string $dbUser
* #param string $dbPassword
* #param string $hostSpec
* #param string $dbName
*/
public function __construct($dbUser, $dbPassword, $hostSpec, $dbName)
{
$this->_dbUser = $dbUser;
$this->_dbPassword = $dbPassword;
$this->_hostSpec = $hostSpec;
$this->_dbName = $dbName;
}
public function Connect()
{
if ($this->_connected && !is_null($this->_db))
{
return;
}
$this->_db = mysqli_connect($this->_hostSpec, $this->_dbUser, $this->_dbPassword,$this->_dbName);
$selected = mysqli_select_db($this->_db, $this->_dbName);
mysqli_set_charset($this->_db, 'utf8');
if (!$this->_db || !$selected)
{
throw new Exception("Error connecting to database\nError: " . mysql_error());
Log::Error("Error connecting to database\n%s", mysql_error());
}
$this->_connected = true;
}
public function Disconnect()
{
mysqli_close($this->_db);
$this->_db = null;
$this->_connected = false;
}
public function Query(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Query: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
return new MySqlReader($result);
}
public function LimitQuery(ISqlCommand $command, $limit, $offset = 0)
{
return $this->Query(new MySqlLimitCommand($command, $limit, $offset));
}
public function Execute(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Execute: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
}
public function GetLastInsertId()
{
return mysqli_insert_id($this->_db);
}
private function _handleError($result, $sqlCommand = null)
{
if (!$result)
{
if ($sqlCommand != null)
{
echo $sqlCommand->GetQuery();
}
throw new Exception('There was an error executing your query\n' . mysql_error());
Log::Error("Error executing MySQL query %s", mysql_error());
}
return false;
}
}
class MySqlLimitCommand extends SqlCommand
{
/**
* #var \ISqlCommand
*/
private $baseCommand;
private $limit;
private $offset;
public function __construct(ISqlCommand $baseCommand, $limit, $offset)
{
parent::__construct();
$this->baseCommand = $baseCommand;
$this->limit = $limit;
$this->offset = $offset;
$this->Parameters = $baseCommand->Parameters;
}
public function GetQuery()
{
return $this->baseCommand->GetQuery() . sprintf(" LIMIT %s OFFSET %s", $this->limit, $this->offset);
}
}
?>
Please someone guide me in this regard
It is very easy and I am providing you a tested answer, first you need to build the Database class as seen below, you need to put it in a file and include it from your homepage (might be the index.php page). Then, you need to initiate an instance of your class from the homepage to connect to the database, the code is very well explained in details in this great article: www.muwakaba.com/php-database-connection
<?php
// Class definition
class Database{
// The constructor function
public function __construct(){
// The properties
$this->host = "your_DB_host_address";
$this->login = "your_DB_login_name";
$this->password = "your_DB_password";
$this->name = "your_DB_name";
// The methods
$this->connect();
$this->select();
}
// The connect function
private function connect(){
$this->connection = mysql_connect($this->host, $this->login, $this->password) or die("Sorry! Cannot connect to the database");
}
// The select function
private function select(){
mysql_select_db($this->name, $this->connection);
}
}
?>

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.

PHP Database Class Load Rows function (OOP)

I want to print out all content of the 'forum_question' table.
What am i doing wrong? No matter what, i will get the message "Nothing found!",
but i am sure the $db->connect DOES work, so it must be something with the query or loadRows functions.
This is my database class:
<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;
public function __construct() {
$this->result = null;
$this->isReady = false;
}
/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }
/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}
public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}
public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}
public function query($sql) {
$this->result = $this->connection->query($sql);
}
public function countRows() {
return $this->result->rowCount(); }
public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}
} // End of Database class
?>
This is my index file:
<?php
require_once 'class_database.php';
$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();
$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();
?>
Why don't you try with different connection script? For instance:
<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
works fine, all you have to do is:
<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();
Assuming that you saved the connection script in file "connection.php".

Categories