mysql pdo连接不上,与MySQL数据库的PDO连接被拒绝

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.

解决方案

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:
';

foreach(PDO::getAvailableDrivers() as $key => $val) {

$key = $key + 1;

echo $key.') '.$val.'
';

}

exit(); //exit and dont proceed

}

$stmt = pdoConnect()->prepare("SELECT * FROM accounts");

$stmt->execute();

I hope it helps!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值