使用本地托管的代码连接到MySQL数据库

使用本地托管的代码连接到MySQL数据库

问题描述:

When I try to run working php code on my localhost instead of the web server, I am getting a connection error.

Warning: mysqli::mysqli() [mysqli.mysqli]: [2002] Connection refused

Any idea how to get the MySQL username, db, and password to work from my local machine? I am using OS X Mountain Lion and Apache.

Do I have to login to the database server and add my IP?

Thanks!

当我尝试在我的localhost而不是Web服务器上运行php代码时,我收到连接错误。 p>

 警告:mysqli :: mysqli()[mysqli.mysqli]:[2002]连接被拒绝
  code>  pre> 
 
 

知道如何从我的本地机器上获取MySQL用户名,数据库和密码吗? 我正在使用OS X Mountain Lion和Apache。 p>

我是否必须登录数据库服务器并添加我的IP? p>

谢谢! p> div>

Unless you've changed the default password root is allowed to connect to localhost, so that would be something like this :

<?php
$mysqli = new mysqli("localhost", "root", "", "");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "
";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "
";
?>

You can replace localhost by an ip, depends on how your database is configured to allow connections, using localhost or an explicit ip.

in case you have downloaded the code from a server and are trying to make a local replica then you need to update the connection parameters to match your local configuration. You need to update username, password , database etc. as per your local settings.. Hostname you may keep as localhost

Respond back if things are not working and add more detail on how things started like how you set up the code locally..and what things you have tried yet..