如何将mysql转换为PDO连接?

时间:2017-02-23 07:38:39

标签: php mysql pdo

如何将mysql代码转换为pdo连接?因为我有一些网络问题。

$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');
}
}

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

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']);
    }
}

希望,这有帮助; - )