I am having some trouble understanding how to correctly reference the following connection file in multiple PHP scripts.
DB Configuration File:
Config.php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASSWORD", "password");
define("DB_DATABASE", "dbName");
?>
Connection File:
DB_Connect.php
<?php
class DB_Connect {
private $conn;
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
?>
Connection Header of a PHP document:
How should the connection header for the following PDO script be written:
<?php
{
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$hostdb;dbname=$namedb;charset=$charset", $userdb, $passdb, $options);
$stmt = $conn->prepare("SELECT `column1`
FROM `Table1` ");
$stmt->execute([]);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($row);
}
?>
First off, this class DB_Connect makes absolutely no sense. In theory it adds some abstract "abstraction" but in reality it's just useless piece of code. So just get rid of it.
Then create a file named pdo.php and add the following code (based on my How to connect to MySQL using PDO canonical example):
$host = '127.0.0.1';
$db = 'dbname';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new \PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
then just include this file in any script that requires a database interaction:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/includes/pdo.php';
$stmt = $pdo->query("SELECT `column1` FROM `Table1` ");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
Note that $_SERVER['DOCUMENT_ROOT'] stuff. it is used to make your file available from any directory. it is explained in my other article on the using correct filesystem paths
class DB_PDO_Connect {
private $db;
// Connecting to database
public function connect() {
if(!isset($this->db)){
require_once 'include/Config.php';
$this->db = new PDO("mysql:dbname=DB_DATABASE;host=DB_HOST;", DB_USER, DB_PASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$this->db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL );
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); // debug
}
return $this->db;
}
}
use
$myPDO =new DB_PDO_Connect();
$conn=$myPDO->connect();
$stmt = $conn->prepare("SELECT `column1` FROM `Table1` ");
//...
Related
I was using the PHP's define() to define constants for my PDO connection string, ie. in mysqli. However, it just didn't seem to work. I kept getting the error: Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'root'#'localhost' (using password: NO) when I used the code below:
The PDO connection string would work when I didn't use PHP's define() function to pass in my connection variables. I'm using PHP 7, MySQL 8, and Apache 2.4.
Problem code below:
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors', 1); // display those if any happen
//Database Connection Constant
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'gallery_db');
echo DB_PASS;
//phpinfo();
//$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
try {
$dbc = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "," . DB_USER, DB_PASS);
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Working Connection Code:
$servername = 'localhost';
$username = 'root';
$password = 'root';
$dbn = 'gallery_db';
//phpinfo();
try {
$dbc = new PDO("mysql:host=$servername;dbname=$dbn", $username, $password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false
));
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Why does PHP define() not work in PDO's connection string?
In the first instance you try this:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.",". DB_USER, DB_PASS);
This only has two arguments, but PDO needs 3:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
https://php.net/manual/en/pdo.connections.php
What happens is that your password constant works but went into the username part of the connection.
Fix:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
Change
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.",". DB_USER, DB_PASS);
to
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
I'm trying to make a MySQL & PHP based control panel for my community. And I've made a settings.php file with arrays with configs. I have class files for functions but there is MySQL function, which will not connect with data I've entered on settings.php..
I've tried other config file options, but none of them works...
on settings.php I have MySQL data like this:
$config['database']['host'] = "---";
$config['database']['user'] = "---";
$config['database']['password'] = "---";
$config['database']['database'] = "---";
And on userdata.php class file, where I'm trying to use those config variables I have:
$mysql = new mysqli($config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['database']);
obviously, on userdata.php I have also required the settings.php..
I was expecting the output to be correct, but it shows only 'wrong MySQL data' errors...
I got it working with settings.php file like:
$config = array (
'db_host' => 'xxx',
'db_user' => 'xxx',
'db_pass' => 'xxx',
'db_database' => 'xxx'
and userdata.php like:
include 'settings.php';
$host = $config['db_host'];
$user = $config['db_user'];
$pass = $config['db_pass'];
$database = $config['db_database'];
$mysql = new mysqli($host, $user, $pass, $database);
you can try this way in connection.php file
<?php
include_once("path/config.php");
function OpenCon()
{
$dbhost = $config['database']['host'];
$dbuser = $config['database']['user'];
$dbpass = $config['database']['password'];
$db = $config['database']['db'];
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n".
$conn -> error);
return $conn;
}
This script
<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysqldg';
$user = 'odbc_dg';
$password = '999999999';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
gives the error *Connection failed: invalid data source name*
I have created an entry in /etc/odbc.ini as follows:
[mysqldg]
Description = DGDB
Driver = mysql537
Database = dg1
Servername = 99.99.99.99
UID = odbc_dg
PWD = 999999
SSLKeyFile = /etc/mysql/ssl/ck.pem
SSLCertFile = /etc/mysql/ssl/cc.pem
SSLCAFile = /etc/mysql/ssl/c1.pem
/etc/odbcinst.ini has the following entry:
[mysql537]
Description = MySQL driver for Plesk
Driver = /usr/lib/odbc2/lib/libmyodcb5w.so
Setup = /usr/lib/odbc2/lib/libmyodbc5w.so
The entry in odbcinst.ini works with a non-DSN connection.
I'm obviously missing something, can anyone help? Thanks.
UPDATED....
I have tried Your Common Sense's code as follows:
<?php
$host = '46.99.199.199';
$db = 'dg';
$user = 'odbc_dg';
$pass = '999999';
$charset = 'utf8mb4';
$options = array(
PDO::MYSQL_ATTR_SSL_KEY => '/etc/mysql/ssl/ck.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/etc/mysql/ssl/cc.pem',
PDO::MYSQL_ATTR_SSL_CA => '/etc/mysql/ssl/c1.pem'
);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
... but I get a connection fail message - Connection failed: SQLSTATE[HY000] [2002]
I think the problem is that the keys I have supplied only work with ODBC
For example this code, which uses odbc_connect works....
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$user = "odbc_dg";
$pass = "99999";
$connection = "Driver= {mysql537};Server=46.99.199.199;Database=dgdb;UID=dgdb;PWD=999999;sslca=/etc/mysql/ssl/c1.pem;sslkey=/etc/mysql/ssl/ck.pem;sslcert=/etc/mysql/ssl/cc.pem";
$con = odbc_connect($connection, $user, $pass);
$sql="SELECT Id from stk_item";
$rs=odbc_exec($con,$sql);
if (!$rs) {
exit("Error in SQL");
}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs)) {
echo odbc_result($rs, "Id"), "\n";
}
odbc_close($con);
echo "</table>";
?>
My problem is that I want to connect to the remote database via pdo because that's the only type of connection allowed in the Drupal synchronising code.
I am having an issue not sure how to get mssql connect to my slim framework with angular js. I have it working with mysql.
part of my helper code
<?php
require_once 'config.php'; // Database setting constants [DB_HOST, DB_NAME, DB_USERNAME, DB_PASSWORD]
class dbHelper {
private $db;
private $err;
function __construct() {
$dsn = 'mssql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
try {
$this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
$response["status"] = "error";
$response["message"] = 'Connection failed: ' . $e->getMessage();
$response["data"] = null;
//echoResponse(200, $response);
exit;
}
}
here is my config code
<?php
/**
* Database configuration
*/
define('DB_USERNAME', 'puma');
define('DB_PASSWORD', 'puma');
define('DB_HOST', 'WIN-F96PF4GQMCS\SQLEXPRESS');
define('DB_NAME', 'angularcode_products');
?>
I have the following lines Of code for a database connection, however I would just want to use my include("config.php") Instead of this long line of code, how would i go about doing that
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh);
Just make a config.php file, for example consider this file is stored in web root (/var/www/), then the contents of the config.php are like this:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
// create LM object, pass in PDO connection
$lm = new lazy_mofo($dbh);
?>
then in your other PHP scripts use the include function:
<?php
include '/var/www/config.php';
...
Now in your PHP scripts you can access the $lm object and $dbh object.
for example include("config.inc.php") and for the config.inc.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=lms;charset=UTF-8', 'root', 'password');
}
catch (PDOException $e) {
die('unable to connect to database ' . $e->getMessage());
}
$lm = new lazy_mofo($dbh);
?>
You can create a db wrapper class in your include file and get really lazy about it =)
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'lms');
define('DB_USER', 'root');
define('DB_PASS', 'password');
class Database{
public function __construct() {
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
$o = new Database();