Trying to figure out how to connect with PDO to MSSQL - php

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');
?>

Related

Refrencing connection file in multiple PHP scripts

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` ");
//...

Does the PHP's define() not work with PDO connection string?

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

Invalid Data Source Name - Connection to MySQL with php, PDO and DSN

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.

php oop pdo connection refused?

I am trying to use connect to database, however I get this error, I am running this on php terminal.
I checked out other sources as well like this one but didn't have the answer I was looking for
Any suggestions or best practices ?
SQLSTATE[HY000] [2002] Connection refusedsomething went wrong
Db.php
<?php
error_reporting(-1);
class Db{
private $db_host;
private $db_user;
private $db_name;
private $db_pass;
public function __construct()
{
$this->db_host = "127.0.0.1";
$this->db_user = "root";
$this->db_pass = "";
$this->db_name = "eli9";
try{
$pdo = new PDO("mysql:host=127.0.0.1;dbname=eli9", $this->db_user, $this->db_pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connected sucessfully \n";
}
catch(PDOexception $e){
echo $e->getMessage();
echo "something went wrong \n";
}
}
}
index.php
<?php
require_once 'Db.php';
$db = new Db();
With the help of #addie code, i was able to find the problem, and it was the following
1) i originally was not using a port number
2) i changed the port number to 8889 instead of 3306
so here is the final code for Db.php
<?php
error_reporting(-1);
class Db{
private $db_host;
private $db_user;
private $db_name;
private $db_pass;
public function __construct()
{
$this->db_host = "127.0.0.1";
$this->db_user = "root";
$this->db_pass = "root";
$this->db_name = "eli9";
try {
$db = new PDO("mysql:host=127.0.0.1;port=8889,dbname=eli9", 'root', 'root');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
echo "connected";
}
catch (PDOException $e){
echo $e->getMessage();
}
}
}
Thank you #addie, but my pervading question is why do i need to include the port in the pdo if that is not the php manual ?
try this, works for me
$pdo = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
you set variable into $this->db_host = "127.0.0.1" but didn't use into connection
try this without class till you get connected and use $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); to check if there any error
also try port 8889
try {
$db = new PDO("mysql:host=127.0.0.1;port=3306,dbname=eli9", 'root', '');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
echo "connected";
}
catch (PDOException $e){
echo $e->getMessage();
}

Using php config file to connect to database instead of PDO connection line

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

Categories