简体   繁体   中英

how can i transform mysql to PDO connection?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM