I have a requirement to connect to two separate databases for a client. One db holds all the standard store data, customers, orders etc, the other is to hold around 41,000 promo codes.
I've looked at PDO to connect to multiple db's as that is the new standard, but i have no idea how to achieve this when we have a configure.php file that contains the db connection info.
configure.php listed below:
define('HTTP_SERVER', 'http://localhost');
define('HTTPS_SERVER', 'https://localhost');
// Use secure webserver for checkout procedure?
define('ENABLE_SSL', 'false');
// NOTE: be sure to leave the trailing '/' at the end of these lines if you make changes!
// * DIR_WS_* = Webserver directories (virtual/URL)
// these paths are relative to top of your webspace ... (ie: under the public_html or httpdocs folder)
define('DIR_WS_CATALOG', '/');
define('DIR_WS_HTTPS_CATALOG', '/');
define('DIR_WS_IMAGES', 'images/');
define('DIR_WS_INCLUDES', 'includes/');
define('DIR_WS_FUNCTIONS', DIR_WS_INCLUDES . 'functions/');
define('DIR_WS_CLASSES', DIR_WS_INCLUDES . 'classes/');
define('DIR_WS_MODULES', DIR_WS_INCLUDES . 'modules/');
define('DIR_WS_LANGUAGES', DIR_WS_INCLUDES . 'languages/');
define('DIR_WS_DOWNLOAD_PUBLIC', DIR_WS_CATALOG . 'pub/');
define('DIR_WS_TEMPLATES', DIR_WS_INCLUDES . 'templates/');
// * DIR_FS_* = Filesystem directories (local/physical)
//the following path is a COMPLETE path to your Zen Cart files. eg: /var/www/vhost/accountname/public_html/store/
define('DIR_FS_CATALOG', '/');
define('DIR_FS_DOWNLOAD', DIR_FS_CATALOG . 'download/');
define('DIR_FS_DOWNLOAD_PUBLIC', DIR_FS_CATALOG . 'pub/');
define('DIR_WS_UPLOADS', DIR_WS_IMAGES . 'uploads/');
define('DIR_FS_UPLOADS', DIR_FS_CATALOG . DIR_WS_UPLOADS);
define('DIR_FS_EMAIL_TEMPLATES', DIR_FS_CATALOG . 'email/');
// define our database connection
define('DB_TYPE', 'mysql');
define('DB_PREFIX', ''); // prefix for database table names -- preferred to be left empty
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', '');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', '');
// The next 2 "defines" are for SQL cache support.
// For SQL_CACHE_METHOD, you can select from: none, database, or file
// If you choose "file", then you need to set the DIR_FS_SQL_CACHE to a directory where your apache
// or webserver user has write privileges (chmod 666 or 777). We recommend using the "cache" folder inside the Zen Cart folder
// ie: /path/to/your/webspace/public_html/zen/cache -- leave no trailing slash
define('SQL_CACHE_METHOD', 'none');
define('DIR_FS_SQL_CACHE', '/enter/your/path/to/public_html_or_htdocs/and/zencart/here/zen/cache');
Digging through the php files i found this, which appears to be where the connection is created:
// Load queryFactory db classes
require(DIR_FS_CATALOG . DIR_WS_CLASSES . 'db/' .DB_TYPE . '/query_factory.php');
$db = new queryFactory();
$db->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
I looked at using:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
in place of the existing:
$db->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
but i'm concerned this means that all the existing queries will need to be changed to cover the $db1, $db2 issue.
Both databases are located on the same server and use identical user/pass combinations.
Any help greatly appreciated.
I tried, and failed with PDO and ended up going with:
$db = new queryFactory();
$db2 = new queryFactory();
$db->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE, USE_PCONNECT, false);
$db2->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE2, USE_PCONNECT, true);
Also had to add the define for DB_DATABASE2 to the configure.php file.
Hope it helps other zen cart users.
Simple really :)
Related
I'm trying to install an existing Moodle app in local to develop a child theme, but it appears the following message after configuring config.php. I'm not able to be aware of the error. That's my file:
<?php
unset($CFG); // Ignore this line
global $CFG; // This is necessary here for PHPUnit execution
$CFG = new stdClass();
$CFG->dbtype = 'mysqli'; // 'mysqli', 'mariadb', 'mysqli', 'mssql', 'sqlsrv' or 'oci'
$CFG->dblibrary = 'native'; // 'native' only at the moment
$CFG->dbhost = 'localhost'; // eg 'localhost' or 'db.isp.com' or IP
$CFG->dbname = '(name)'; // database name, eg moodle
$CFG->dbuser = '(same as above)'; // your database username
$CFG->dbpass = '(pass)'; // your database password
$CFG->prefix = 'pztp_'; // prefix to use for all table names
$CFG->dboptions = array(
'dbpersist' => false, // should persistent database connections be
// used? set to 'false' for the most stable
// setting, 'true' can improve performance
// sometimes
'dbsocket' => false, // should connection via UNIX socket be used?
// if you set it to 'true' or custom path
// here set dbhost to 'localhost',
// (please note mysql is always using socket
// if dbhost is 'localhost' - if you need
// local port connection use '127.0.0.1')
'dbport' => '3306', // the TCP port number to use when connecting
// to the server. keep empty string for the
// default port
);
$CFG->wwwroot = 'http://'.$_SERVER['SERVER_NAME'];
$CFG->dataroot = 'C:/wamp64/www/example/data';
$CFG->directorypermissions = 02777;
$CFG->admin = 'admin';
require_once(dirname(__FILE__) . '/lib/setup.php'); // Do not edit
dbname, dbuser and dbpass are censored due to privacy politics, as well as application name, but two first are the same value and the name of the "root" folder (named example) is given in dataroot path. I've created that user and DB in the DBMS, I've assigned all the privileges to the user for that DB and I've imported the DB. I use PHP 7.0.33 (that can't be updated) due to the Moodle version. I've tried using XAMPP and WAMP with the same result.
Thank you all in advance!
Maybe try creating a test PHP file - in the Moodle root folder - to test the connection to see if its Moodle or the database.
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname, $dbport);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
I have a simple php file that is connect to the wordpress DB and any thing that want works fine. But I want to use the value from wp_config.php file from wordpress to connect my php file to DB. I tried this but it's not working
<?php
require_once('wp-config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD , DB_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
And this is my default PHP file that works. This file is in a directory inside the WordPress project that I use inside the other template for a custom search.
// Create connection
$conn = new mysqli($servername, $username, $password , $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Note: I change the important Data!
Do you have a solution for this?
You really should be using PDO to connect, but other than that, perhaps try using constant("variable") instead of trying to use the variables directly:
<?php
require_once('wp-config.php');
$conn = new mysqli(constant("DB_HOST"), constant("DB_USER"), constant("DB_PASSWORD"), constant("DB_NAME"));
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
The same code works fine for me.
Check the wp-config.php path and try to echo the constants and
check you have included the correct file before passing to mysqli
echo DB_HOST;
echo DB_USER;
echo DB_PASSWORD;
echo DB_NAME;
or you can use wp-load.php include('/path/wp-load.php');
include_once ('/path/wp-load.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD , DB_NAME);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
Since you want to connect WP DB in other external application or in a template to get data from WP DB you can include wordpress file directly in your file.
using wp-blog-header.php will load complete wordpress into your current template and then you can use make use of it.
include_once $_SERVER['DOCUMENT_ROOT'].'/YOUR_WP_DIR/wp-blog-header.php';
global $wpdb; // wordpress database object
print_r($wpdb);
Content of wp-blog-header.php:
/**
* Loads the WordPress environment and template.
*
* #package WordPress
*/
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' );
}
Using the defines the user sets in wp-config:
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
Since your script is outside the Wordpress environment, try this:
require_once(path/to/wp-config.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
How do i compress these two following database connection codes into one code?
Code1
<?Php
define($base_url = 'http://example.com/url/'); // Change this to your site URL and Path
define($from_email = 'example#email.com'); // Change this email id to your id
///////// Database Details change here ////
define($dbhost_name = 'mysql.host.com');
define($database = 'databasename123');
define($username = 'username123');
define($password = 'password123');
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Code2
<?php
define('DB_HOST', 'mysql.host.com');
define('DB_NAME', 'databasename123');
define('DB_USER','username123');
define('DB_PASSWORD','password123');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(header('Location: ./admin/install.php'));
$db=mysql_select_db(DB_NAME,$con) or die(header('Location: ./admin/install.php'));
?>
If there is no possibilities, what is the best way to solve this problem?
Thank you on beforehand
One of your snippets uses PDO and the other uses mysql_connect. Combining them completely is non-trivial, however you could put your database host, name, username and password as variables in another file and then include that file in both the bits of code you have provided. That would at least mean you could update all the database details in one place.
I am trying to connect to my database via PHP but get blank page when I run through Safari(http://pushchat.local:11111/test/databasename.php)
I can see my datbasename.php file under http://pushchat.local:11111/test/ as shown below:
Following is my PHP code:
try
{
if (!defined('APPLICATION_ENV'))
define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : ‘development’);
require_once '../api_config.php';
$config = $config[APPLICATION_ENV];
$pdo = new PDO(
'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'],
$config['db']['username'],
$config['db']['password'],
array());
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('SET NAMES utf8');
echo 'Database connection successful!';
}
catch (Exception $e)
{
echo 'Could not connect to the database. Reason: ' . $e;
}
I even tried to put a stop sigh using codebug but I think it never stops.
Thanks for your help.
You're missing a closing quote -
'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'].'',
-----------------------------------------------------------------------------^
Note the additional single-quote which balances the line. Error checking would have caught this.
I'm Sorry But I'm Seeing database.php Not databasename.php.
Have You Even Checked If The File Exists?
Also Connecting To The Database Should Be Typed In Config File & You should require It In You're Main PHP File.
For Example The Config File Should Look Like This:
<?php
$connection = mysql_connect('localhost', 'root', 'password'); //here is the host, username and password of mysql account.instead of localhost type in your websites domain name.
if (!$connection){ //and instead of password,type in your own password.
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
& The Main PHP Should Look Like this:
<?php
require('config.php'); //requires the config.php page
//rest of the code goes here...
?>
Also On Line 10,You Have Missed A Closing Single-Quote.
Can any please explain what does it mean
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
and it's giving me an Error
"Error: Could not load database file mysql!"
file contents
define('DB_DRIVER', 'mysql');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'XXX');
define('DB_PASSWORD', 'XXX');
define('DB_DATABASE', 'XXXX');
DB CLASS Constructor
public function __construct($driver, $hostname, $username, $password, $database) {
if (file_exists(DIR_DATABASE . $driver . '.php')) {
require_once(DIR_DATABASE . $driver . '.php');
} else {
exit('Error: Could not load database file ' . $driver . '!');
}
$this->driver = new $driver($hostname, $username, $password, $database);
}
You don't have driver for mysql database, check DIR_DATABASE folder for existence of the mysql.php file.
Assuming you're using OpenCart, have a look in your config.php file. Find a line that looks like the following:
define('DIR_DATABASE', '/something/something/system/database/');
Make sure the something/something is valid for your site. In particular, ensure the path points to a directory containing the mysql.php driver file. You'll probably find it doesn't, so you'll need to edit it so that it does.
You should also check that the Apache service user has privileges to access that file.