php连接到mysqlworkbench localhost

I have a mac with OSX 10.8.4. I have installed my localhost and it works just fine. I have made a php script, from where I would like to connect MySQL workbench database to. My apache tomcat server runs, and also mysql on the computer, and I use XAMPP. This is my code:

    <?php 

 // Establish connection to DB using PDO
 try {
  $pdo = new PDO('127.0.0.1:3306', 'root', '');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
  echo "Connected!";
 } catch (PDOException $e) {  
  $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
  echo "Connection failed";

  exit();
 }

I have tried this script to connect to a remote mysql server, where it works fine, but I cannot use it for my localhost. I also tried just to put in localhost in new PDO, but still the same. Does anybody have a clue to what is wrong?

Best Regards Mads

douqu2481
douqu2481 你确定mysql在你的localhost上运行吗?
大约 7 年之前 回复
doujiu7680
doujiu7680 MySQLWorkbench不是数据库管理系统。MySQL是。
大约 7 年之前 回复
dpt62283
dpt62283 您是否检查了端口号以及更改主机?您的本地MySql服务器是否具有您需要的用户名和密码?
大约 7 年之前 回复

1个回答

You'll have an easier time knowing what's not working if you echo the exception being thrown.

Your code

} catch (PDOException $e) {  
  $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
  echo "Connection failed";
}

doesn't actually print the exception! Try this instead:

} catch (PDOException $e) {
    $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
    echo $error;
}

That will at least give you some helpful debugging info.

dtiopy6088
dtiopy6088 并非所有人都使用xampp .l需要与php.ini一起使用,因为l手动安装
一年多之前 回复
doufen3091
doufen3091 您可能需要在php.ini中启用它。 在XAMPP控制面板中,单击Apache Module的“Config”按钮,然后单击“PHP(php.ini)”。 搜索包含类似于:extension = php_pdo_mysql.dll的行并删除;。 然后保存该文件,并重新启动apache。 注意:我在Windows上运行xampp,所以显然你不会在mac上搜索.dll - 但是找一下与pdo_mysql相关的行,并取消注释它。
大约 7 年之前 回复
dongquxiao8545
dongquxiao8545 嗯它无论如何都没有解决问题,所以如果有人仍然有想法我会喜欢它:-)
大约 7 年之前 回复
duancai7568
duancai7568 这应该可以解决问题:<?php //使用PDO建立与DB的连接尝试{$ pdo = new PDO('mysql:127.0.0.1:3306','root',''); $ pdo-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION); $ pdo-> exec('SET NAMES“utf8”'); echo“已连接!”; } catch(PDOException $ e){$ error ='错误 - 连接到数据库失败:'。 $ E->的getMessage(); echo $ error; 出口(); }?>
大约 7 年之前 回复
doukang2003
doukang2003 too long
大约 7 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐