open cart displaying Deprecated: mysql_connect() message on top - php

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

Related

PHP:How to take backup of mysql database according to the given time period (eg :last6 months)

This code is used to backup mysql database. I want to modify the code given below as it performs taking backup according to the given time period .expecting your help.
Class DBBackup {
/**
*
* The host you will connect
* #var String
*/
private $host;
/**
*
* The driver you will use to connect
* #var String
*/
private $driver;
/**
*
* The user you will use to connect to a database
* #var String
*/
private $user;
/**
*
* The password you will use to connect to a database
* #var String
*/
private $password;
/**
*
* The database you will use to connect
* #var String
*/
private $dbName;
/**
*
* String to connect to the database using PDO
* #var String
*/
private $dsn;
/**
*
* Array with the tables of the database
* #var Array
*/
private $tables = array();
/**
*
* Hold the connection
* #var ObjectConnection
*/
private $handler;
/**
*
* Array to hold the errors
* #var Array
*/
private $error = array();
/**
*
* The result string. String with all queries
* #var String
*/
private $final;
/**
*
* The main function
* #method DBBackup
* #uses Constructor
* #param Array $args{host, driver, user, password, database}
* #example $db = new DBBackup(array('host'=>'my_host', 'driver'=>'bd_type(mysql)', 'user'=>'db_user', 'password'=>'db_password', 'database'=>'db_name'));
*/
public function DBBackup($args){
if(!$args['host']) $this->error[] = 'Parameter host missing';
if(!$args['user']) $this->error[] = 'Parameter user missing';
if(!isset($args['password'])) $this->error[] = 'Parameter password missing';
if(!$args['database']) $this->error[] = 'Parameter database missing';
if(!$args['driver']) $this->error[] = 'Parameter driver missing';
if(count($this->error)>0){
return;
}
$this->host = $args['host'];
$this->driver = $args['driver'];
$this->user = $args['user'];
$this->password = $args['password'];
$this->dbName = $args['database'];
$this->final = 'CREATE DATABASE ' . $this->dbName.";\n\n";
if($this->host=='localhost'){
// We have a little issue in unix systems when you set the host as localhost
$this->host = '127.0.0.1';
}
$this->dsn = $this->driver.':host='.$this->host.';dbname='.$this->dbName;
$this->connect();
$this->getTables();
$this->generate();
}
/**
*
* Call this function to get the database backup
* #example DBBackup::backup();
*/
public function backup(){
//return $this->final;
if(count($this->error)>0){
return array('error'=>true, 'msg'=>$this->error);
}
return array('error'=>false, 'msg'=>$this->final);
}
/**
*
* Generate backup string
* #uses Private use
*/
private function generate(){
foreach ($this->tables as $tbl) {
$this->final .= '--CREATING TABLE '.$tbl['name']."\n";
$this->final .= $tbl['create'] . ";\n\n";
$this->final .= '--INSERTING DATA INTO '.$tbl['name']."\n";
$this->final .= $tbl['data']."\n\n\n";
}
$this->final .= '-- THE END'."\n\n";
}
/**
*
* Connect to a database
* #uses Private use
*/
private function connect(){
try {
$this->handler = new PDO($this->dsn, $this->user, $this->password);
} catch (PDOException $e) {
$this->handler = null;
$this->error[] = $e->getMessage();
return false;
}
}
/**
*
* Get the list of tables
* #uses Private use
*/
private function getTables(){
try {
$stmt = $this->handler->query('SHOW TABLES');
$tbs = $stmt->fetchAll();
$i=0;
foreach($tbs as $table){
$this->tables[$i]['name'] = $table[0];
$this->tables[$i]['create'] = $this->getColumns($table[0]);
$this->tables[$i]['data'] = $this->getData($table[0]);
$i++;
}
unset($stmt);
unset($tbs);
unset($i);
return true;
} catch (PDOException $e) {
$this->handler = null;
$this->error[] = $e->getMessage();
return false;
}
}
/**
*
* Get the list of Columns
* #uses Private use
*/
private function getColumns($tableName){
try {
$stmt = $this->handler->query('SHOW CREATE TABLE '.$tableName);
$q = $stmt->fetchAll();
$q[0][1] = preg_replace("/AUTO_INCREMENT=[\w]*./", '', $q[0][1]);
return $q[0][1];
} catch (PDOException $e){
$this->handler = null;
$this->error[] = $e->getMessage();
return false;
}
}
/**
*
* Get the insert data of tables
* #uses Private use
*/
private function getData($tableName){
try {
$stmt = $this->handler->query('SELECT * FROM '.$tableName);
$q = $stmt->fetchAll(PDO::FETCH_NUM);
$data = '';
foreach ($q as $pieces){
foreach($pieces as &$value){
$value = htmlentities(addslashes($value));
}
$data .= 'INSERT INTO '. $tableName .' VALUES (\'' . implode('\',\'', $pieces) . '\');'."\n";
}
return $data;
} catch (PDOException $e){
$this->handler = null;
$this->error[] = $e->getMessage();
return false;
}
}
}
?>
Use crontab (chrono table) to perfoms it :
just must create a simple php file what use your class.
define the time period on the server side (using crontab -e command) and call the file
Note: you must got a ssh access to the server.
More information here.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 3 bytes) in E:\library\Zend\Db\Adapter\Pdo\Abstract.php on line 144

I am a beginner in Zend and php. Please excuse me if I am absurd and silly.
I am doing my first application in Zend,called thenexsocial, with the help of the tutorials available online. But I get this Fatal error every time I refresh the browser. I referred all the posts regarding this in Stack exchange, but couldn't solve the problem.
The error occurs in the "Abstract.php of Pdo folder in the Zend library".
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#zend.com so we can send you a copy immediately.
*
* #category Zend
* #package Zend_Db
* #subpackage Adapter
* #copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
* #version $Id$
*/
/**
* #see Zend_Db_Adapter_Abstract
*/
require_once 'Zend/Db/Adapter/Abstract.php';
/**
* #see Zend_Db_Statement_Pdo
*/
require_once 'Zend/Db/Statement/Pdo.php';
/**
* Class for connecting to SQL databases and performing common operations using PDO.
*
* #category Zend
* #package Zend_Db
* #subpackage Adapter
* #copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Db_Adapter_Pdo_Abstract extends Zend_Db_Adapter_Abstract
{
/**
* Default class name for a DB statement.
*
* #var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Pdo';
/**
* Creates a PDO DSN for the adapter from $this->_config settings.
*
* #return string
*/
protected function _dsn()
{
// baseline of DSN parts
$dsn = $this->_config;
// don't pass the username, password, charset, persistent and driver_options in the DSN
unset($dsn['username']);
unset($dsn['password']);
unset($dsn['options']);
unset($dsn['charset']);
unset($dsn['persistent']);
unset($dsn['driver_options']);
// use all remaining parts in the DSN
foreach ($dsn as $key => $val) {
$dsn[$key] = "$key=$val";
}
return $this->_pdoType . ':' . implode(';', $dsn);
}
/**
* Creates a PDO object and connects to the database.
*
* #return void
* #throws Zend_Db_Adapter_Exception
*/
protected function _connect()
{
// if we already have a PDO object, no need to re-connect.
if ($this->_connection) {
return;
}
// get the dsn first, because some adapters alter the $_pdoType
$dsn = $this->_dsn();
// check for PDO extension
if (!extension_loaded('pdo')) {
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
}
// check the PDO driver is available
if (!in_array($this->_pdoType, PDO::getAvailableDrivers())) {
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The ' . $this->_pdoType . ' driver is not currently installed');
}
// create PDO connection
$q = $this->_profiler->queryStart('connect', Zend_Db_Profiler::CONNECT);
// add the persistence flag if we find it in our config array
if (isset($this->_config['persistent']) && ($this->_config['persistent'] == true)) {
$this->_config['driver_options'][PDO::ATTR_PERSISTENT] = true;
}
try {
$this->_connection = new PDO(
$dsn,
$this->_config['username'],
$this->_config['password'],
$this->_config['driver_options']
);
$this->_profiler->queryEnd($q);
// set the PDO connection to perform case-folding on array keys, or not
$this->_connection->setAttribute(PDO::ATTR_CASE, $this->_caseFolding);
// always use exceptions.
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
ini_set("memory_limit", -1);
}
}
/**
* Test if a connection is active
*
* #return boolean
*/
public function isConnected()
{
return ((bool) ($this->_connection instanceof PDO));
}
/**
* Force the connection to close.
*
* #return void
*/
public function closeConnection()
{
$this->_connection = null;
}
/**
* Prepares an SQL statement.
*
* #param string $sql The SQL statement with placeholders.
* #param array $bind An array of data to bind to the placeholders.
* #return PDOStatement
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* On RDBMS brands that don't support sequences, $tableName and $primaryKey
* are ignored.
*
* #param string $tableName OPTIONAL Name of table.
* #param string $primaryKey OPTIONAL Name of primary key column.
* #return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
$this->_connect();
return $this->_connection->lastInsertId();
}
/**
* Special handling for PDO query().
* All bind parameter names must begin with ':'
*
* #param string|Zend_Db_Select $sql The SQL statement with placeholders.
* #param array $bind An array of data to bind to the placeholders.
* #return Zend_Db_Statement_Pdo
* #throws Zend_Db_Adapter_Exception To re-throw PDOException.
*/
public function query($sql, $bind = array())
{
if (empty($bind) && $sql instanceof Zend_Db_Select) {
$bind = $sql->getBind();
}
if (is_array($bind)) {
foreach ($bind as $name => $value) {
if (!is_int($name) && !preg_match('/^:/', $name)) {
$newName = ":$name";
unset($bind[$name]);
$bind[$newName] = $value;
}
}
}
try {
return parent::query($sql, $bind);
} catch (PDOException $e) {
/**
* #see Zend_Db_Statement_Exception
*/
require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Executes an SQL statement and return the number of affected rows
*
* #param mixed $sql The SQL statement with placeholders.
* May be a string or Zend_Db_Select.
* #return integer Number of rows that were modified
* or deleted by the SQL statement
*/
public function exec($sql)
{
if ($sql instanceof Zend_Db_Select) {
$sql = $sql->assemble();
}
try {
$affected = $this->getConnection()->exec($sql);
if ($affected === false) {
$errorInfo = $this->getConnection()->errorInfo();
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($errorInfo[2]);
}
return $affected;
} catch (PDOException $e) {
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Quote a raw string.
*
* #param string $value Raw string
* #return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
$this->_connect();
return $this->_connection->quote($value);
}
/**
* Begin a transaction.
*/
protected function _beginTransaction()
{
$this->_connect();
$this->_connection->beginTransaction();
}
/**
* Commit a transaction.
*/
protected function _commit()
{
$this->_connect();
$this->_connection->commit();
}
/**
* Roll-back a transaction.
*/
protected function _rollBack() {
$this->_connect();
$this->_connection->rollBack();
}
/**
* Set the PDO fetch mode.
*
* #todo Support FETCH_CLASS and FETCH_INTO.
*
* #param int $mode A PDO fetch mode.
* #return void
* #throws Zend_Db_Adapter_Exception
*/
public function setFetchMode($mode)
{
//check for PDO extension
if (!extension_loaded('pdo')) {
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
}
switch ($mode) {
case PDO::FETCH_LAZY:
case PDO::FETCH_ASSOC:
case PDO::FETCH_NUM:
case PDO::FETCH_BOTH:
case PDO::FETCH_NAMED:
case PDO::FETCH_OBJ:
$this->_fetchMode = $mode;
break;
default:
/**
* #see Zend_Db_Adapter_Exception
*/
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Invalid fetch mode '$mode' specified");
break;
}
}
/**
* Check if the adapter supports real SQL parameters.
*
* #param string $type 'positional' or 'named'
* #return bool
*/
public function supportsParameters($type)
{
switch ($type) {
case 'positional':
case 'named':
default:
return true;
}
}
/**
* Retrieve server version in PHP style
*
* #return string
*/
public function getServerVersion()
{
$this->_connect();
try {
$version = $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
} catch (PDOException $e) {
// In case of the driver doesn't support getting attributes
return null;
}
$matches = null;
if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) {
return $matches[1];
} else {
return null;
}
}
}
The error occurs in the following line:
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
Please help me. Thank you.
Increase memory limit in your php.ini file
OR
set memory limit like - ini_set("memory_limit","10M"); in your project's configuration file

mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in "link to the file" [duplicate]

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.

Accessing a database [closed]

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!

How can I make a singleton wrapper for PDO?

How can I make a singleton of the PDO extention? Extending doesn't work, because I get a fatal error when I try it ...
You don't need a Singleton.
But to answer this nevertheless:
You cannot turn a public visibility to a stricter visibility. So PDO cannot have the constructor's visibility changed to anything but public. So you need to wrap the PDO instance into a Singleton:
class MyPdo
{
/**
* #var MyPdo
*/
protected static $_instance;
/**
* #var Pdo
*/
protected $_pdo;
/**
* Creates instance and returns it on subsequent calls
*
* #throws InvalidArgumentException
* #param array $options PDO connection data
* #returns MyPdo
*/
public static function getInstance(array $options = NULL)
{
if(self::$_instance === NULL) {
if($options === NULL) {
throw new InvalidArgumentException(
'You must supply connection options on first run');
}
// call constructor with given options and assign instance
self::$_instance = new self(
$options['dsn'],
$options['user'],
$options['password'],
$options['driver_options']
);
}
return self::$_instance;
}
/**
* Creates new MyPdo wrapping a PDO instance
*
* #throws PDOException
* #param String $dsn
* #param String $user
* #param String $password
* #param Array $driver_options
* #return void
*/
private function __construct($dsn, $user, $password, $driver_options)
{
try {
$this->_pdo = new PDO($dsn, $user, $password, $driver_options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
/**
* Singletons may not be cloned
*/
private function __clone() {}
/**
* Delegate every get to PDO instance
*
* #param String $name
* #return Mixed
*/
public function __get($name)
{
return $this->_pdo->$name;
}
/**
* Delegate every set to PDO instance
*
* #param String $name
* #param Mixed $val
* #return Mixed
*/
public function __set($name, $val)
{
return $this->_pdo->$name = $val;
}
/**
* Delegate every method call to PDO instance
*
* #param String $method
* #param Array $args
* #return Mixed
*/
public function __call($method, $args) {
return call_user_func_array(array($this->_pdo, $method), $args);
}
}
You'd use it like this:
$db = MyPdo::getInstance(array(
'dsn'=>'mysql:dbname=mysql;host=127.0.0.1',
'user' => 'root',
'password' => 'minnymickydaisydonaldplutogoofysanfrancisco',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)));
$version = $db->query( 'SELECT version();' );
echo $version->fetchColumn();
// remove reference to instance
unset($db);
// doesn't require connection data now as it returns same instance again
$db = MyPdo::getInstance();
$version = $db->query( 'SELECT version();' );
echo $version->fetch();

Categories