how can i transform mysql to PDO connection? - php

How can I transform the mysql code bellow into pdo connection ? because i have some networking issues.
$gaSql['user'] = "root";
$gaSql['password'] = "";
$gaSql['db'] = "test";
$gaSql['server'] = "localhost";
// DB connection
function dbinit(&$gaSql) {
// if error rezults 500
function fatal_error($sErrorMessage = '') {
header($_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error');
die($sErrorMessage);
}
// connecting to mysql
if ( !$gaSql['link'] = #mysql_connect($gaSql['server'], $gaSql['user'], $gaSql['password']) ) {
fatal_error('Could not open connection to server');
}
// select the DB
if ( !mysql_select_db($gaSql['db'], $gaSql['link']) ) {
fatal_error('Could not select database');
}
}

Proper PDO db connection
<?php
$host = '127.0.0.1';
$db = 'your db';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $options);
?>
Reference : https://phpdelusions.net/pdo
I use this in all my pdo connections it works perfectly

You could try something like this:
try {
$pdo = new PDO('mysql:host=' . $gaSql['server'] . ';dbname=' . $gaSql['db'], $gaSql['user'], $gaSql['password']);
} catch (PDOException $ex) {
if ($ex->getCode() == 1049) {
throw new Exception('Unknown Database: ' . $gaSql['db']);
} elseif ($ex->getCode() == 1045) {
throw new Exception('Wrong credentials for user: ' . $gaSql['user']);
}
}
Hope, this helps ;-)

Related

Combining connect data into one file

I have a PHP file that I use to include when I connect to my db. It looks something like this:
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
I also have a second database that I frequently access at the same time as the first one. Can I combine both connections like this or is there a better way of doing it?
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr1";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$database = "mydb2";
$username = "my_usr2";
$password = "mypas2db2";
try {
$db2 = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Assuming you're not using Classes, you could DRY (Do-not Repeat Yourself) up your code a little like the following. This allows for extending into even further databases/users/servers in the future if required:
<?php
$connections = [
'db1' => [
'host' = 'localhost';
'database' = 'mydb1';
'username' = 'my_usr1';
'password' = 'mypas2db1';
],
'db2' => [
'host' = 'localhost';
'database' = 'mydb2';
'username' = 'my_usr2';
'password' = 'mypas2db2';
],
];
function getDatabaseConnection($connectionName = 'db1'): ?PDO
{
global $connections;
if (empty($connections[$connectionName]) {
// Throw an exception because this connection doesn't exist.
throw new \Exception(
"Connection: {$connectionName} not specified."
);
}
$data = $connections[$connectionName];
$dbHost = $data['host'] ?: 'localhost';
$dbUsername = $data['username'] ?: '';
$dbPassword = $data['password'] ?: '';
$dbName = $data['database'] ?: '';
if (!$dbUsername || !$dbName) {
// We don't have a username or database to connect to. Fail.
throw new \Exception(
'No valid database name or user provided.'
);
}
$db = new PDO(
"mysql:host={$dbHost};dbname={$dbName};charset=UTF8",
$dbUsername,
$dbPassword
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
// We don't need to specify a connection because we want the default, db1.
$db1 = getDatabaseConnection();
// Specify we want a connection to db2.
$db2 = getDatabaseConnection('db2');

Pending PDO connection - medoo php

When I change the IP of my MySQL connection and run this:
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
The try and catch does not work. Its does not catch that error, PDOException or general exception.
The problem is that I did not get any error or a response from PDO. It is pending for a long time.
How can I get the response immediately if there are no connections?
Full code:
case 'mysql':
if ($this->socket) {
$dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
} else {
$dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
}
$commands[] = 'SET SQL_MODE=ANSI_QUOTES';
if (in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) && $this->charset) {
$commands[] = "SET NAMES '" . $this->charset . "'";
}
//**here is the problem //
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
foreach ($commands as $value) {
$this->pdo->exec($value);
}
} catch (PDOException $e) {
echo "Connection to database lost";
}
catch (Exception $e) {
echo "Connection to database lost";
return;
}
even if I try from php manual
$dsn = 'mysql:host=127.0.0.2;port=3306;dbname=dbname';
$username = 'user';
$password = 'pass';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);

Failing testing database connection in php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}

connect for 2 Databases

There is a problem with a connection to DB.
Used class for DB
class DB
{
public static $connect = false;
private $database_host = 'localhost';
private $database_user = '';
private $database_pass = '';
private $database_db = '';
private $database_type = 'mysql';
function __construct($database_host, $database_db, $database_user, $database_pass)
{
$this->database_host = $database_host;
$this->database_db = $database_db;
$this->database_user = $database_user;
$this->database_pass = $database_pass;
if (self::$connect === false) {
$this->connect();
}
}
private function connect()
{
$dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;
try {
self::$connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//var_dump(self::$connect);
if(!self::$connect) {
die("Cannot connect to DB");
}
} catch (PDOException $e) {
die("Cannot connect to DB");
}
}
}
This connect, for 2 DB
$connect = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);
$connectSlave = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);
First connect - good, second - Fatal error: Access to undeclared static property: DB::$connectSlave
Please help me.
$connect should be an instance variable instead of static (otherwise it's shared between DB instances):
public $connect = false;
Then use $this->connect instead of self::$connect. Here's your class:
class DB
{
public $connect = false;
private $database_host = 'localhost';
private $database_user = '';
private $database_pass = '';
private $database_db = '';
private $database_type = 'mysql';
function __construct($database_host, $database_db, $database_user, $database_pass)
{
$this->database_host = $database_host;
$this->database_db = $database_db;
$this->database_user = $database_user;
$this->database_pass = $database_pass;
if ($this->connect === false) {
$this->connect();
}
}
private function connect()
{
$dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;
try {
$this->connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//var_dump(self::$connect);
if(!$this->connect) {
die("Cannot connect to DB");
}
} catch (PDOException $e) {
die("Cannot connect to DB");
}
}
}

Function for connecting to mysql database

I made my first function for connecting to mysql database. I have index.php and functions.php and i included functions.php to index.php!
This is my Connect to database function...
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", $username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dhb;
}
I don't know is it correct and if i am calling it right.
I type in index.php
<?php
require_once 'functions.php';
connect_to_database();
active_links();
include 'includes/head.php';
include 'includes/nav.php';
..................
See comments:
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
$dbh = false; // initialized for error
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1",
$username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
// consider to exit / throw own exception / stop continuing script anyhow ....
}
// returns false on error
return $dbh; // typo here, was $dhb !!
}
Usage:
$DB = connect_to_database();
if ( $DB !== false )
$DB->function();
So it works fine now, here is the answer! Thank you for help
I created file named config.php
// PDO connect *********
function connect()
{
$host = 'localhost';
$db_name = 'database_name';
$db_user = 'root';
$db_password = '';
return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
and just calling connect function like this, $pdo = connect(); or any name for var but that is the way!
<?php
include 'config.php';
$pdo = connect();
........

Categories