问题
I am trying to connect to my NearlyFreeSpeech MySQL database. I can login through PHPMyAdmin but not through PDO. I am using this code
$dbconn = new PDO('mysql:host=127.0.0.1;dbname='.$config['db'].'; port=3307', $config['user'], $config['pass']);
Where $config is defined in a separate file. The error I get is:
Warning: PDO::__construct() [pdo.--construct]: [2002] Connection refused (trying to connect via tcp://127.0.0.1:3307)
Error: SQLSTATE[HY000] [2002] Connection refused
and then eventually
Fatal error: Call to a member function query() on a non-object in...
If I use
mysql:host=localhost
The error I get is
Error: SQLSTATE[HY000] [2002] No such file or directory
Now I assume "Connection refused" is better than "No such file or directory", but I don't know where to go from here. Any idea why this is happening? Thank you for your help.
回答1:
Try my existing functions and constant variables, you may also change those constant to an array variable you have.
define("SERVER_SQL_VERSION","mysql");
define("SQL_SERVER","localhost");
define("SQL_PORT","3306");
define("SQL_USERNAME","root");
define("SQL_PASSWORD","");
define("SQL_DB_NAME","db");
if(!function_exists('pdoConnect')) {
function pdoConnect() {
$pdo = new PDO(SERVER_SQL_VERSION.":host=".SQL_SERVER.";dbname=".SQL_DB_NAME."", "".SQL_USERNAME."", "".SQL_PASSWORD."");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
There might be an issue about your concatenation, this must be working...
I also seperated the SERVER_SQL_VERSION, and added a functions to check if the driver is available...I am using the XAMPP software and only mysql and sqlite is active, if you/others try to use postgresql and so on...that must be working as well.
if(!function_exists('check_sql_version')) {
function check_sql_version() {
$sql_available = false; //make it false yet
foreach(PDO::getAvailableDrivers() as $key => $val) {
if(SERVER_SQL_VERSION == $val)
{
$sql_available = true;
}
}
//check now if sql_available is true or false
if($sql_available == true)
return true;
else
return false;
}
}
So a sample should be considered:
if(!check_sql_version()) {
echo '('.SERVER_SQL_VERSION.') is not available, you only have this drivers:<br/>';
foreach(PDO::getAvailableDrivers() as $key => $val) {
$key = $key + 1;
echo $key.') '.$val.'<br/>';
}
exit(); //exit and dont proceed
}
$stmt = pdoConnect()->prepare("SELECT * FROM accounts");
$stmt->execute();
I hope it helps!
来源:https://stackoverflow.com/questions/16267727/pdo-connection-to-mysql-database-refused