This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am running a MySQL database with Mac OS X Lion Server. I have a PHP script running on my server that wants to access a database. The PHP script is here:
/Library/Server/Web/Data/Sites/Default
The database is here:
/usr/local/mysql
How do I get the PHP script to access the database if they are not in the same directory (the database is above it). Thanks for your help!
Here is the error I am experiencing:
Connect failed: No such file or directory?There seems to have been a slight problem with our database, please try again later.<br /><br />? <textarea rows="10" cols="80">MySQL Error:???42??Error: ?Error #: ? Filename:
And in my PHP file, this is the code I use to access the database:
$this->DB_HOST = '67.85.14.141';
$this->DB_USERNAME = 'username';
$this->DB_PASSWORD = 'password';
$this->DB_DATABASE = 'Carillons';
Rest of code below:
/**
* Begin Document
*/
class DbConnect
{
/**
* Connection to MySQL.
*
* #var string
*/
var $link;
/**
* Holds the most recent connection.
*
* #var string
*/
var $recent_link = null;
/**
* Holds the contents of the most recent SQL query.
*
* #var string
*/
var $sql = '';
/**
* Holds the number of queries executed.
*
* #var integer
*/
var $query_count = 0;
/**
* The text of the most recent database error message.
*
* #var string
*/
var $error = '';
/**
* The error number of the most recent database error message.
*
* #var integer
*/
var $errno = '';
/**
* Do we currently have a lock in place?
*
* #var boolean
*/
var $is_locked = false;
/**
* Show errors? If set to true, the error message/sql is displayed.
*
* #var boolean
*/
var $show_errors = false;
/**
* Log errors? If set to true, the error message/sql is logged.
*
* #var boolean
*/
public $log_errors = false;
/**
* The Database.
*
* #var string
*/
public $DB_DATABASE;
/**
* The variable used to contain a singleton instance of the database connection.
*
* #var string
*/
static $instance;
/**
* The number of rows affected by the most recent query.
*
* #var string
*/
public $affected_rows;
public $insert_id;
/**
* Constructor. Initializes a database connection and selects our database.
*/
function __construct()
{
$this->DB_HOST = '67.85.14.141';
$this->DB_USERNAME = 'username'; // !!! CHANGE ME
$this->DB_PASSWORD = 'password'; // !!! CHANGE ME
$this->DB_DATABASE = 'Carillons'; // !!! CHANGE ME
}
/**
* Singleton pattern to retrieve database connection.
*
* #return mixed MySQL database connection
*/
function _get($property)
{
if(self::$instance == NULL)
{
self::$instance = $this->connect();
}
return self::$instance->$property;
}
/**
* Singleton pattern to retrieve database connection.
*
* #return mixed MySQL database connection
*/
function Connection()
{
if(self::$instance == NULL)
{
self::$instance = $this->connect();
}
return self::$instance;
}
/**
* Connect to the Database.
*
*/
function connect()
{
self::$instance = new mysqli($this->DB_HOST, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if (mysqli_connect_errno()) {
$this->raise_error(printf("Connect failed: %s\n", mysqli_connect_error()));
}
return self::$instance;
}
/**
* Executes a sql query. If optional $only_first is set to true, it will
* return the first row of the result as an array.
*
* #param string Query to run
* #param bool Return only the first row, as an array?
* #return mixed
*/
function query($sql, $only_first = false)
{
if(self::$instance == NULL)
{
self::$instance = $this->connect();
}
$this->recent_link =& self::$instance;
$this->sql =& $sql;
if(!$result = self::$instance->query($sql))
{
$this->raise_error(printf("Connect failed: %s\n", self::$instance->error));
}
$this->affected_rows = self::$instance->affected_rows;
$this->insert_id = self::$instance->insert_id;
$this->query_count++;
if ($only_first)
{
$return = $result->fetch_array(MYSQLI_ASSOC);
$this->free_result($result);
return $return;
}
return $result;
}
/**
* Fetches a row from a query result and returns the values from that row as an array.
*
* #param string The query result we are dealing with.
* #return array
*/
function fetch_array($result)
{
return #mysql_fetch_assoc($result);
}
/**
* Returns the number of rows in a result set.
*
* #param string The query result we are dealing with.
* #return integer
*/
function num_rows($result)
{
return self::$instance->num_rows;
}
/**
* Retuns the number of rows affected by the most recent query
*
* #return integer
*/
function affected_rows()
{
return self::$instance->affected_rows;
}
/**
* Returns the number of queries executed.
*
* #param none
* #return integer
*/
function num_queries()
{
return $this->query_count;
}
/**
* Lock database tables
*
* #param array Array of table => lock type
* #return void
*/
function lock($tables)
{
if (is_array($tables) AND count($tables))
{
$sql = '';
foreach ($tables AS $name => $type)
{
$sql .= (!empty($sql) ? ', ' : '') . "$name $type";
}
$this->query("LOCK TABLES $sql");
$this->is_locked = true;
}
}
/**
* Unlock tables
*/
function unlock()
{
if ($this->is_locked)
{
$this->query("UNLOCK TABLES");
}
}
/**
* Returns the ID of the most recently inserted item in an auto_increment field
*
* #return integer
*/
function insert_id()
{
return self::$instance->insert_id;
}
/**
* Escapes a value to make it safe for using in queries.
*
* #param string Value to be escaped
* #param bool Do we need to escape this string for a LIKE statement?
* #return string
*/
function prepare($value, $do_like = false)
{
if(self::$instance == NULL)
{
self::$instance = $this->connect();
}
if ($do_like)
{
$value = str_replace(array('%', '_'), array('\%', '\_'), $value);
}
return self::$instance->real_escape_string($value);
}
/**
* Frees memory associated with a query result.
*
* #param string The query result we are dealing with.
* #return boolean
*/
function free_result($result)
{
return #mysql_free_result($result);
}
/**
* Turns database error reporting on
*/
function show_errors()
{
$this->show_errors = true;
}
/**
* Turns database error reporting off
*/
function hide_errors()
{
$this->show_errors = false;
}
/**
* Closes our connection to MySQL.
*
* #param none
* #return boolean
*/
function close()
{
$this->sql = '';
return self::$instance->close();
}
/**
* Returns the MySQL error message.
*
* #param none
* #return string
*/
function error()
{
$this->error = (is_null($this->recent_link)) ? '' : self::$instance->error;
return $this->error;
}
/**
* Returns the MySQL error number.
*
* #param none
* #return string
*/
function errno()
{
$this->errno = (is_null($this->recent_link)) ? 0 : self::$instance->errno ;
return $this->errno;
}
/**
* Gets the url/path of where we are when a MySQL error occurs.
*
* #access private
* #param none
* #return string
*/
function _get_error_path()
{
if ($_SERVER['REQUEST_URI'])
{
$errorpath = $_SERVER['REQUEST_URI'];
}
else
{
if ($_SERVER['PATH_INFO'])
{
$errorpath = $_SERVER['PATH_INFO'];
}
else
{
$errorpath = $_SERVER['PHP_SELF'];
}
if ($_SERVER['QUERY_STRING'])
{
$errorpath .= '?' . $_SERVER['QUERY_STRING'];
}
}
if (($pos = strpos($errorpath, '?')) !== false)
{
$errorpath = urldecode(substr($errorpath, 0, $pos)) . substr($errorpath, $pos);
}
else
{
$errorpath = urldecode($errorpath);
}
return $_SERVER['HTTP_HOST'] . $errorpath;
}
/**
* If there is a database error, the script will be stopped and an error message displayed.
*
* #param string The error message. If empty, one will be built with $this->sql.
* #return string
*/
function raise_error($error_message = '')
{
if ($this->recent_link)
{
$this->error = $this->error($this->recent_link);
$this->errno = $this->errno($this->recent_link);
}
if ($error_message == '')
{
$this->sql = "Error in SQL query:\n\n" . rtrim($this->sql) . ';';
$error_message =& $this->sql;
}
else
{
$error_message = $error_message . ($this->sql != '' ? "\n\nSQL:" . rtrim($this->sql) . ';' : '');
}
$message = "<textarea rows=\"10\" cols=\"80\">MySQL Error:\n\n\n$error_message\n\nError: {$this->error}\nError #: {$this->errno}\nFilename: " . $this->_get_error_path() . "\n</textarea>";
if (!$this->show_errors)
{
$message = "<!--\n\n$message\n\n-->";
}
else die("There seems to have been a slight problem with our database, please try again later.<br /><br />\n$message");
}
}
?>
MySQL is not accessed based on files.
As long as it is running you just need the server name username and password to the mysql databse.
I'm a java coder but mysql database is something you can connect to over the network wo any access to the local filesystem. basically you'd need the php library or module that talks to the mysql db which just might be a standard plugin. For java its a specific library called connector for j.
To get a connection to the db what Neal said is correct, you just need the hostname or ip, username, password, and database name. sometimes this is all combined into something called the database connection string.
Here's a link that might help as i'm not fluent in php:
http://www.w3schools.com/php/php_mysql_connect.asp
good luck!
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have thinking of this from past an hour, but unable to understand the best way to add update, Insert feature using a class in PHP.
I have an employee table which has around 5 columns, so i have created different properties for it in my Employees Class.
Now i am unable to understand where to set these Values, in __costructor(), in add_employees() method or some other way..
If i set them in __constructor() then user must remember and follow the same pattern in writing arguments that i followed in writing the parameters.
I am unable to understand that is it a right way or should i use different approach to do this.
I have searched this on net, and found very complex examples, where people are taking argument in form of array, separating it, add loop in it and then put it into database.
Class Employees(){
public $db;
public $conn;
public $emp_id;
public $first_name;
public $last_name;
public $gender;
public $added_by;
public function __construct(){
$this->db= new DatabaseConnection('localhost', 'root', '', 'employeesmanagement');
$this->conn= $this->db->connectDb();
}
public function get_employees(){
}
public function add_employees(){
}
I've written a class before, that does only things related to database things. Here is the class
/**
* CLASS: Database
*
* Description: This class deals with all database connection
* across the website. If any class needs to use the database
* it has to extends this one.
*
* #author: Andre Ferraz
* #copyright: ^
* #version: 2.0
*/
class Database
{
/**
* Holds Class Object instance
*
* #var Object
* #access: Private
* #static
*/
private static $_instace;
/**
* Holds PDO Object
*
* #var PDO
* #access: Private
*/
private $_pdo;
/**
* Used to keep track of how many columns
* has been found!
*
* #var int
* #access: Private
*/
private $_count;
/**
* Holds data from database
*
* #var array
* #access: Private
*/
private $_results = array();
/**
* Description: Instantiates PDO object
*
* #access: Protected
*/
protected function __construct()
{
$host = Config::get("database:host");
$user = Config::get("database:username");
$pass = Config::get("database:password");
$dbna = Config::get("database:dbname");
try
{
$this->_pdo = new PDO("mysql:dbname=".$dbna.";host=".$host.";", $user, $pass);
}
catch(PDOException $e)
{
Redirect::to(500);
}
}
/**
* Description: Gets data from the database
*
* #access: protected
* #return boolean
*/
protected function get($table, $columns, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
if($query->execute())
{
$this->_count = $query->rowCount();
if($this->_count > 0)
{
$this->_results = $query->fetchAll();
return true;
}
return false;
}
}
return false;
//#todo condition == null
}
/**
* Description: Very similar to get function, but
* instead it just checks if data exists without storing
* any data.
*
* #access: protected
* #return boolean
*/
protected function query($table, $columns, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
if($query->execute())
{
$this->_count = $query->rowCount();
return(($this->_count > 0)? true : false);
}
}
return false;
//#todo condition == null
}
/**
* Description: Updates information on the database
*
* #access: protected
*/
protected function update($table, $CV = array(), $condition)
{
if($CV !=null)
{
$columns = '';
$x = 1;
foreach($CV as $key => $value)
{
$columns .= "$key='$value'";
if($x < count($CV))
{
$columns .= ",";
}
$x++;
}
$query = $this->_pdo->prepare("UPDATE $table SET $columns WHERE $condition");
if($query->execute())
return true;
else
return false;
}
return false;
}
/**
* Description: Inserts data into database
*
* #access: protected
*/
protected function insert($table, $CV = array())
{
if($CV !=null)
{
// Join array elements with a string
$columns = implode(", ", array_keys($CV));
$values = '';
$x = 1;
// Put array key values into variables
foreach($CV as $value)
{
$values .= "'".$value."'";
if($x < count($CV))
{
$values .= ', ';
}
$x++;
}
$query = $this->_pdo->prepare("INSERT INTO $table ($columns) VALUES({$values})");
// Check execution is successful
if($query->execute())
return true;
else
return false;
}
return false;
}
/**
* Description: Deletes data from the database
*
* #access: protected
*/
protected function delete($table, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("DELETE FROM $table WHERE $condition");
if($query->execute())
return true;
else
return false;
}
else
{
$query = $this->_pdo->prepare("DELETE FROM $table");
if($query->execute())
return true;
else
return false;
}
}
protected function getResults()
{
return $this->_results;
}
/**
* Description: Singleton pattern, prevents multiple
* instantiations of the same class.
*
* NOTE: This is not needed. Only for "show of"
*
* #access: public
* #static
* #return Object
*/
public static function instance()
{
if(isset(self::$_instace))
return self::$_instace;
else
self::$_instace = new self;
}
}
Which other classes like User class would extend and use all the necessary function from the database to get data related to the user. Have a look at the project. There are some bugs in a few classes (which I can't be bothered to fix at this point), but database class is working fine. I don't mind if you get reference from it.
Visit my github for the full project.
Github
I have created a timeclock system for a website admin area I am working on. But I want to use a class to handle the code in a better way so I am starting over. So far I have 2 classes. One to handle the database connection and the queries to the database through PDO.
When starting the class for the timeclock (Which I am having to build from scratch) I am getting close because I am no longer receiving errors when I load the page. But the results of the query are not right as I should be returning "true" instead of NULL for a record coming from the database. Can someone please help me understand what I am doing wrong.
My Database class is like so(From GitHub)...
/**
* DB - A simple database class
*
* #author Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
* #git https://github.com/indieteq/PHP-MySQL-PDO-Database-Class
* #version 0.2ab
*
*/
require("Log.class.php");
class DB
{
# #object, The PDO object
private $pdo;
# #object, PDO statement object
private $sQuery;
# #array, The database settings
private $settings;
# #bool , Connected to the database
private $bConnected = false;
# #object, Object for logging exceptions
private $log;
# #array, The parameters of the SQL query
private $parameters;
/**
* Default Constructor
*
* 1. Instantiate Log class.
* 2. Connect to database.
* 3. Creates the parameter array.
*/
public function __construct()
{
$this->log = new Log();
$this->Connect();
$this->parameters = array();
}
/**
* This method makes connection to the database.
*
* 1. Reads the database settings from a ini file.
* 2. Puts the ini content into the settings array.
* 3. Tries to connect to the database.
* 4. If connection failed, exception is displayed and a log file gets created.
*/
private function Connect()
{
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'acro_1986';
//$this->settings = parse_ini_file("settings.ini.php");
$dsn = 'mysql:dbname='.$dbname.';host='.$host.'';
try
{
# Read settings from INI file, set UTF8
$this->pdo = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
# We can now log any exceptions on Fatal error.
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Disable emulation of prepared statements, use REAL prepared statements instead.
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
# Connection succeeded, set the boolean to true.
$this->bConnected = true;
}
catch (PDOException $e)
{
# Write into log
echo $this->ExceptionLog($e->getMessage());
die();
}
}
/*
* You can use this little method if you want to close the PDO connection
*
*/
public function CloseConnection()
{
# Set the PDO object to null to close the connection
# http://www.php.net/manual/en/pdo.connections.php
$this->pdo = null;
}
/**
* Every method which needs to execute a SQL query uses this method.
*
* 1. If not connected, connect to the database.
* 2. Prepare Query.
* 3. Parameterize Query.
* 4. Execute Query.
* 5. On exception : Write Exception into the log + SQL query.
* 6. Reset the Parameters.
*/
private function Init($query,$parameters = "")
{
# Connect to database
if(!$this->bConnected) { $this->Connect(); }
try {
# Prepare query
$this->sQuery = $this->pdo->prepare($query);
# Add parameters to the parameter array
$this->bindMore($parameters);
# Bind parameters
if(!empty($this->parameters)) {
foreach($this->parameters as $param)
{
$parameters = explode("\x7F",$param);
$this->sQuery->bindParam($parameters[0],$parameters[1]);
}
}
# Execute SQL
$this->succes = $this->sQuery->execute();
}
catch(PDOException $e)
{
# Write into log and display Exception
echo $this->ExceptionLog($e->getMessage(), $query );
die();
}
# Reset the parameters
$this->parameters = array();
}
/**
* #void
*
* Add the parameter to the parameter array
* #param string $para
* #param string $value
*/
public function bind($para, $value)
{
$this->parameters[sizeof($this->parameters)] = ":" . $para . "\x7F" . utf8_encode($value);
}
/**
* #void
*
* Add more parameters to the parameter array
* #param array $parray
*/
public function bindMore($parray)
{
if(empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
/**
* If the SQL query contains a SELECT or SHOW statement it returns an array containing all of the result set row
* If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows
*
* #param string $query
* #param array $params
* #param int $fetchmode
* #return mixed
*/
public function query($query,$params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$query = trim($query);
$this->Init($query,$params);
$rawStatement = explode(" ", $query);
# Which SQL statement is used
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->sQuery->fetchAll($fetchmode);
}
elseif ( $statement === 'insert' || $statement === 'update' || $statement === 'delete' ) {
return $this->sQuery->rowCount();
}
else {
return NULL;
}
}
/**
* Returns the last inserted id.
* #return string
*/
public function lastInsertId() {
return $this->pdo->lastInsertId();
}
/**
* Returns an array which represents a column from the result set
*
* #param string $query
* #param array $params
* #return array
*/
public function column($query,$params = null)
{
$this->Init($query,$params);
$Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);
$column = null;
foreach($Columns as $cells) {
$column[] = $cells[0];
}
return $column;
}
/**
* Returns an array which represents a row from the result set
*
* #param string $query
* #param array $params
* #param int $fetchmode
* #return array
*/
public function row($query,$params = null,$fetchmode = PDO::FETCH_ASSOC)
{
$this->Init($query,$params);
return $this->sQuery->fetch($fetchmode);
}
/**
* Returns the value of one single field/column
*
* #param string $query
* #param array $params
* #return string
*/
public function single($query,$params = null)
{
$this->Init($query,$params);
return $this->sQuery->fetchColumn();
}
/**
* Writes the log and returns the exception
*
* #param string $message
* #param string $sql
* #return string
*/
private function ExceptionLog($message , $sql = "")
{
$exception = 'Unhandled Exception. <br />';
$exception .= $message;
$exception .= "<br /> You can find the error back in the log.";
if(!empty($sql)) {
# Add the Raw SQL to the Log
$message .= "\r\nRaw SQL : " . $sql;
}
# Write into log
$this->log->write($message);
return $exception;
}
}
My Timeclock class...
class Timeclock {
public $user_id;
public function __construct($user_id) {
$this->user_id = $user_id ;
$this->db = new Db();
//$this->clocked_in = is_user_clocked_in($user_id);
}
public function is_user_clocked_in(){
$result = $this->db->query("SELECT * FROM timeclock WHERE user_id = :user_id AND time_out IS NULL", array("user_id"=>$this->user_id));
if ( count ( $result ) > 0 ){
return $result[0];
}else{
return null;
}
}
}
And I am calling it like so...
if (isset($_SESSION['admin'])) {
$_user_id = $_SESSION['admin'][0]['user_id'];
// calls action and determines case
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'home';
}
$action = strtolower($action);
switch ($action) {
case 'home':
$timeclock = new Timeclock($_user_id);
$user = new Timeclock($timeclock->user_id);
$clocked_in = $user->is_user_clocked_in();
include ('dashboard.php');
break;
}
}
Also, is it possible to have every function in the class (Once its done) run one after the other and fill in the declared variables at the top (Once I have added them of course) so I can just call the class and have it run through once? Or will I have to call each function individually on demand?
Thanks for the attempt to help #Ohgodwhy. $clocked_in was returning an array because I asked it to select all columns in the table. So when there was a result, it was an array. I changed the return of the function to return true instead of $result[0] because I only need to know if the user is logged in. I could have probably just changed the query to select that column as well. After doing that, it worked great until I provided a value for the table field (Making the user clocked_in). I then got a Undefined offset:0 error because I was trying to call the value of $result[0] when there was no array indexed because the query obviously returns array(0); I just changed the count to check to see if $result exists.
updated code is as follows in case someone comes across this
Timeclock Class
class Timeclock {
public $user_id;
public function __construct($user_id) {
$this->user_id = $user_id ;
$this->db = new Db();
//$this->clocked_in = is_user_clocked_in($user_id);
}
public function is_user_clocked_in(){
$result = $this->db->query("SELECT * FROM timeclock WHERE user_id = :user_id AND time_out IS NULL", array("user_id"=>$this->user_id));
if ( count ($result) > 0 ){
return true;
}else{
return null;
}
}
}
I installed open cart on my local server, but it is displaying a message at top.
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\new\htdocs\business\system\database\mysql.php on line 6
How can I fix it ?
This error is because you're using PHP 5.5 or above. The best solution to this is to not suppress errors as others have said (since that prevents you seeing errors from other issues) but to install a mysqli extension/PDO extension for OpenCart. This one is free and works well - it's the one I use
I am using opencart-1.5.6.1.zip on ApacheFriends XAMPP Version 1.8.3 and I see this error message on every page too.
Open opencart/config.php and opencart/admin/config.php.
Edit 'mysql' -> 'mysqli'
e.g.
//define('DB_DRIVER', 'mysql');
define('DB_DRIVER', 'mysqli');
Save the files and no need to restart anything. The error message is gone.
below is the code for PDO in opencart 1.5.6 or <
<?php
/**
* Class for working with database (PDO)
*
* #property \PDO $dbh
*
* #author WebImperia Dev
* #since 0.0.1
*/
final class OC_PDO
{
/**
* Link to the database connection
*
* #var \PDO
*/
private $dbh;
/**
* List of connection settings
*
* #var array
*/
private $options = array(
'PDO::ATTR_ERRMODE' => PDO::ERRMODE_SILENT
);
/**
* The number of rows affected by the last operation
*
* #var int
*/
private $affectedRows = 0;
/**
* The data for the database connection
*
* #var \stdClass
*/
private $params = array();
/**
* Sets the connection and connects to the database
*
* #param string $host server Address
* #param string $user Username
* #param string $pass Password
* #param string $name The database name
* #param string $charset Encoding connection
*/
public function __construct($host, $user, $pass, $name, $charset = 'utf8')
{
$this->params = new stdClass;
# keep connection data
$this->params->host = $host;
$this->params->user = $user;
$this->params->pass = $pass;
$this->params->name = $name;
$this->params->charset = $charset;
$this->params->connstr = "mysql:host={$host};dbname={$name};charset={$charset}";
# add the connection parameters
$this->options['PDO::MYSQL_ATTR_INIT_COMMAND'] = "SET NAMES '{$charset}'";
$this->connect();
}
/**
* Connect to database
*/
public function connect()
{
try {
$this->dbh = new PDO($this->params->connstr, $this->params->user, $this->params->pass, $this->options);
if (version_compare(PHP_VERSION, '5.3.6', '<=')) {
$this->dbh->exec($this->options['PDO::MYSQL_ATTR_INIT_COMMAND']);
}
} catch (PDOException $exception) {
trigger_error($exception->getMessage());
}
}
/**
* Query the database
*
* #param string $sql
* #return \stdClass
*/
public function query($sql = null)
{
if ($this->dbh) {
$data = new stdClass;
$sth=$this->dbh->prepare($sql);
$sth->execute();
//$sth= $this->dbh->query($sql);
$this->affectedRows = $sth->rowCount();
$data->rows = $sth ? $sth->fetchAll() : array();
$data->row = isset($data->rows[0]) ? $data->rows[0] : null;
$data->num_rows = $this->affectedRows;
return $data;
}
return null;
}
/**
* Concludes the string in quotation marks to be used in the query
*
* #param mixed $string shielded line
* #return string Returns shielded line or to FALSE , if the driver does not support screening
*/
public function escape($string = null)
{
return $this->dbh ? $this->dbh->quote($string) : null;
}
/**
* Gets the number of rows affected by the last operation
*
* #return int
*/
public function countAffected()
{
return $this->affectedRows;
}
/**
* Gets the ID of the last inserted row or sequence of values
*
* #return int
*/
public function getLastId()
{
return $this->dbh ? $this->dbh->lastInsertId() : 0;
}
/**
* Gets the name of the driver
*
* #return string|null
*/
public function getDriverName()
{
return $this->dbh ? $this->dbh->getAttribute(PDO::ATTR_DRIVER_NAME) : null;
}
/**
* Get information about the version of the client libraries that are used by the PDO driver
*
* #return string|null
*/
public function getVersion()
{
return $this->dbh ? $this->dbh->getAttribute(PDO::ATTR_CLIENT_VERSION) : null;
}
/**
* Closing a database connection
*/
public function close()
{
$this->dbh = null;
}
public function __destruct()
{
$this->close();
}
}
I recently moved one of my sites to a new dedicated server running the latest version of PHP. In my php-based Knowledgebase section of the site, I am getting the following error:
Strict Standards: Declaration of API_RATING::multiDelete() should be compatible with API::multiDelete($ids = 0) in /home/givebrad/public_html/kb/lib/api/class.rating.php on line 156
Line 156 is the last closing } at the bottom of the file. Below is the code for class-rating.php. Can anyone help me out to figure out how to fix this?
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'class.api.php');
class API_RATING extends API
{
var $rateid = 0;
var $questionid = 0;
var $ip = '';
var $ratedat = '';
var $fields = array (
'rateid',
'questionid',
'ip',
'ratedat',
'ratingemail',
'ratingmessage'
);
var $pk = 'rateid';
/**
* create
* create a new rating in the database
*
* #return bool was the creation successful ?
*/
function create()
{
$_POST['ratedat'] = date('Y-m-d H:i:s');
$_POST['ip'] = $_SERVER['REMOTE_ADDR'];
return parent::create();
}
/**
* multiDelete
* Delete multiple rating ids. Update each associated question.
*
* #return bool was the delete successful?
*/
function multiDelete($ids) {
//Get the question ids
$objArray = $this->loadMultiByPK($ids);
foreach ($objArray as $rateObj) {
$questionObj = new API_QUESTION();
$questionObj->load($rateObj->questionid);
$questionObj->negvotes--;
$questionObj->score -= SCORE_MODIFIER;
$questionObj->updateField("negvotes", $questionObj->negvotes);
$questionObj->updateField("score", $questionObj->score);
}
//Delete from the main table
if (!parent::multiDelete($ids)) {
return false;
}
return true;
}
/**
* validate_rateid
*
* Ensure the rate id is a pos int
*
* #param string $var
*
* #return bool
*/
function validate_rateid($var)
{
return $this->is_positive_int($var);
}
/**
* validate_questionid
*
* Ensure the questionid is pos int
*
* #return bool
*/
function validate_questionid($var)
{
return $this->is_positive_int($var);
}
/**
* validate_ip
*
* Ensure the ip is an ipv4 address
*
* #param $var the ip to validate
*
* #return bool
*/
function validate_ip($var)
{
return $this->is_ip($var);
}
/**
* validate_ratedat
*
* Ensure the rated at date is in the standard date format
*
* #param string $var
*
* #return bool
*/
function validate_ratedat($var)
{
return $this->is_standard_date($var);
}
/**
* validate_email
*
* Ensure the email address for this rate entry is valid.
*
* #param string $var
*
* #return bool
*/
function validate_ratingemail(&$var)
{
if ((trim($var) == "") || (trim($var) == GetLang("WhyUnhelpfulEmail"))) {
$var = "";
return true;
} else {
return is_email_address($var);
}
}
/**
* validate_ratingmessage
*
* Ensure there is a message and its not blank.
*
* #param string $var
*
* #return bool
*/
function validate_ratingmessage(&$var)
{
if (strlen(trim($var)) > 250) {
$var = substr(trim($var),0,250);
return true;
} else {
return (trim($var) != "");
}
}
}
?>
This function :
function multiDelete($ids) {
Should be identic with it's parent function, find out the same function in class API, the nums, default value and type of the params should be same;
I asked this before, Strict Standards: Declaration of ' ' should be compatible with ' '
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 1 year ago.
I have this error in a Component in Joomla
That's my code (the error is in line 263):
<?php
/**
* #package Joomla.Platform
* #subpackage Database
*
* #copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* #package Joomla.Platform
* #subpackage Database
* #see http://php.net/manual/en/book.mysqli.php
* #since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* #var string
* #since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* #param array $options List of options used to configure the connection
*
* #since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = #mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET ##SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* #since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* #param string $text The string to be escaped.
* #param boolean $extra Optional parameter to provide extra escaping.
*
* #return string The escaped string.
*
* #since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* #return boolean True on success, false otherwise.
*
* #since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* #return boolean True if connected to the database engine.
*
* #since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* #return integer The number of affected rows.
*
* #since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* #return JDatabaseExporterMySQLi An exporter object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* #return JDatabaseImporterMySQLi An importer object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* #param resource $cursor An optional database cursor resource to extract the row count from.
*
* #return integer The number of returned rows.
*
* #since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* #param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* #return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* #return string The database connector version.
*
* #since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* #return boolean True if supported.
*
* #since 11.1
* #deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* #return integer The value of the auto-increment field from the last inserted row.
*
* #since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* #return mixed A database cursor resource on success, boolean false on failure.
*
* #since 11.1
* #throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* #param string $database The name of the database to select for use.
*
* #return boolean True if the database was successfully selected.
*
* #since 11.1
* #throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* #return boolean True on success.
*
* #since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
* #param string $class The class name to use for the returned row object.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return void
*
* #since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* #param boolean $abortOnError Abort on error.
* #param boolean $transactionSafe Transaction safe queries.
*
* #return mixed A database resource if successful, false if not.
*
* #deprecated 12.1
* #since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
As the link Jon Conde provided says, you are getting this because you have an error in your query. You have not provided the query so it's impossible to know what the problem is. Unfortunately some of the advice you are getting on the whole is going to make it worse because the problem is not in JDatabaseQueryMysqli it is in the code where you are calling it. You are getting a boolean false instead of the expected results because your query has failed.
To see your generated query you can use
echo $query->dump();
put it before you are calling getNumRows(). You may need a die; depending on the context or just log it or if in the cms you can turn on the debugger and see the generated queries (global configuration, debug on).
If you provide your code (not a copy of the api) then people can help debug your query.
I will say it's a bug that it's not testing for that and throwing an exception if your query has failed.
If you're using joomla 2.5, please check again of your php version ; It must be php 5.3 at least.