Reputation: 86
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');
}
}
Upvotes: 0
Views: 50
Reputation: 4772
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
Upvotes: 2
Reputation: 1
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 ;-)
Upvotes: 0