i have the following problem which costs me the last couple of hours...
i have a class for mysqli connections:
class database extends SplObjectStorage{
private $db_link;
public function __construct($MySQLi_DB){
if(!file_exists($_SERVER["HOME"].'/'.(substr($_SERVER['PHP_SELF'], 1, strpos(substr($_SERVER['PHP_SELF'], 1),'/'))).'/includes/mysqli.inc.php')){
echo "MySQLi Include Datei nicht vorhanden";
}else{
if (!$this->create_connection($MySQLi_DB) == true){
echo "Error creating Database. Parameter '".$MySQLi_DB."' unknown<br><br>";
}
}
}
public function query($query){
Return $this->db_link->query($query);
}
public function close(){
mysqli_close($this->db_link);
}
private function create_connection($MySQLi_DB){
include_once($_SERVER["HOME"].'/'.(substr($_SERVER['PHP_SELF'], 1, strpos(substr($_SERVER['PHP_SELF'], 1),'/'))).'/includes/mysqli.inc.php');
$this->db_link = new mysqli($MySQLi_Host, $MySQLi_User, $MySQLi_Passw, $MySQLi_Praefix.$MySQLi_DB);
$this->attach($this->db_link);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQLi: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
return false;
}else{
return true;
}
echo $mysqli->host_info . "\n";
}
The constructor initializes the class by looking for an include-file which contains all connectiondata like user, pwd, etc.
it although receive a parameter ($MySQLi_DB) which is similar to the databasename.
When i call this class with this command:
$SSO_DB = new database('SSO');
This class works fine.
Changing the parameter do another databasename is no problem.
e.g.: $Social_DB = new database('social');
This is even no problem until i call two instanzes of my class on the same page!
e.g.:
$SSO_DB = new database('SSO');
$Social_DB = new database('social');
Returns this error:
Warning: mysqli::mysqli(): (HY000/1044): Access denied for user ''#'localhost' to database 'social' in /volume1/web/portal/classes/database.class.php on line 41
Line 41 is:
$this->db_link = new mysqli($MySQLi_Host, $MySQLi_User, $MySQLi_Passw, $MySQLi_Praefix.$MySQLi_DB);
When i remove one of the classcalls no error.
No matter which call i remove...
Any idea?
changing include_once() into include() solved the problem! php seems to store how often the class is called on one page and did not included the file a second time.
Related
Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case
Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43
The following is my connection file:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = #new mysqli("localhost","root#localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
This is my class:
<?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the #new mysqli parameters. Can anyone help me to understand what is going wrong?
Probably somewhere you have DBconnection->close(); and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)
Reason of the error is wrong initialization of the mysqli object. True construction would be like this:
$DBConnect = new mysqli("localhost","root","","Ladle");
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Check if db name do not have "_" or "-"
that helps in my case
I have a very straightforward SELECT query within the context of a PHP class which is returning false (failed) but I am unable to retrieve the associated error information. The odd thing is that the call worked fine until I had to reorganize the mysql database - without revising the PHP code obviously it fails - the result is false - but where is the error message?
Code is as follows:
<?php
class Database {
private $_connection;
private $_result;
private $_lastQuery;
private $_error;
public function __construct($dbase) {
$this->_connection = new mysqli(DB_SERVER, DB_USER, DB_PASS, $dbase);
if (mysqli_connect_error()) {
trigger_error("failed to connect to MySQL: " . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($this->_connection, 'utf8');
}
public function query($query) {
$this->_lastQuery = $query;
$this->_result = mysqli_query($this->_connection, $query);
$this->_error = $this->_connection->error;
return $this->_result;
}
}
No error string appears in $this->_error; also not revealed when inspected during debugging (PHPStorm).
When executing the query via the command line, the (expected) error messaging is generated.
It appears that the problem is actually with xdebug.
I have an issue that I can't figure out. I have a class Database which if I use it directly I connect to db regularly. I have another class Categories and I want to call a Database object. The problem is that if I call $db->connect in categories does not work. I tried call mysql_connect directly in Categories and it works fine!
Why can't I use $db->connect (the error is Access denied for user 'user'#'0.0.0.0' (using password: YES).
My code in class Database is:
public function connect($new_link=false){
$this->link_id = #mysql_connect($this->server,$this->user,$this->pass,$new_link);
echo "<br/>link_id = ".$this->link_id;
if (!$this->link_id){//open failed
$this->oops("Could not connect to server: <b>$this->server</b>.");
}
else{
echo "Connected to server <br/>";
}
if(!#mysql_select_db($this->database, $this->link_id)){//no database
$this->oops("Could not open database: <b>$this->database</b>.");
}
else{
echo "Database opened <br/>";
}
// unset the data so it can't be dumped
$this->server='';
$this->user='';
$this->pass='';
$this->database='';
}#-#connect()
My code in class Category is:
public static function selectAll() { // SELECT All Function
$db = Database::obtain();
// connect to the server
$db->connect();
$sql = "SELECT * FROM productCategory";
$rows = $db->fetch_array($sql);
return $rows;
}
Database::obtain code
public static function obtain($server=null, $user=null, $pass=null, $database=null){
if (!self::$instance){
self::$instance = new Database($server, $user, $pass, $database);
}
return self::$instance;
}#-#obtain()
Am I doing sth wrong, that I can't see?
Well, the error message is "Access denied for user 'user'#'0.0.0.0'"
That means when you instantiate your class with $db = Database::obtain(); You don't set the values for server, user, pass, database. Probably the class Database implements a singleton pattern, and the method obtain() just returns the instance without any properties set.
I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array