2016-07-08 96 views
0

我一直在试图设置一个Sql数据库,但我无法得到它在PHP中连接。这里就是我的代码如下所示:mySql数据库连接到错误的服务器

$conn = mysql_connect("my_sql_here.net","root",'my_password_here'); 
print $conn; 
mysql_select_db("my_database",$conn); 

$created = mysql_query("SELECT * FROM `inventory`); 
if(!$created) { 
print "error: "; 
print mysql_error(); 
} 
print json_encode($created); 
mysql_close($conn); 

当我运行这段代码,我得到:

error: Access denied for user 'dom710'@'localhost' (using password: NO)false

为什么tryng连接到本地主机?为什么试图使用root作为密码? 我感到非常困惑。

+1

您应该考虑从MySQL切换,因为它[已正式](http://php.net/manual/en/migration55.deprecated.php)已弃用。使用[MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)**与** [已准备好的语句]( http://php.net/manual/en/pdo.prepared-statements.php)。我建议在上面提到的选项之一中重写它,并忘记所有关于MySQL的内容,因为您是初学者,最好从最佳实践出发,而不是学习旧的过时实践。 – Script47

+0

我无法按照陈述重现此问题。这个脚本是否包含在其他东西中? –

+0

噢,你应该在你的语法中有一个错误,因为你在查询中缺少'''(双引号) – Script47

回答

0

考虑使用PDO建立连接:

// Establish a connection 
$host = 'my_sql_here.net'; 
$name = 'my_database'; 
$user = 'root'; 
$pass = 'my_password_here'; 

$dsn = "mysql:dbname=$name;host=$host;charset=utf8"; 
$conn = new PDO($dsn, $user, $pass); 

// Perform your query 
$query = 'SELECT * FROM `inventory`'; 
$statement = $conn->prepare($query); 
$statement->execute(); 
$resultSet = $statement->fetchAll(); 

// Do stuff with your $resultSet 
0

你已经配置了安全模式。这就是为什么它试图连接到本地主机。

https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-connect.html $server “在SQL安全模式,则忽略此参数和价值的 'localhost:3306' 总是使用。” $username“在SQL安全模式下,忽略此参数并使用拥有服务器进程的用户的名称。”

而正如有人在评论中指出的,不应该使用这个函数,因为它已被弃用。

+0

如何告诉它不要以安全模式启动Isn'默认关闭? – Zock77

+0

http://nl1.php.net/manual/en/ini.core.php#ini.sql.safe-mode默认值是0,但在某些Linux发行版中可能会被忽略。你的phpinfo()来查看它是否打开或关闭 – user11235813

相关问题