我正在尝试从PHP函数中连接mysql。凭据存储在一个单独的PHP文件中,我将其包含在函数中。但是当我运行脚本时,我收到了以下错误:
Warning: mysql_query(): A link to the server could not be established in C:\xamp
p\htdocs\abc\test.php on line 12. Access denied for user 'ODBC'@'localhost' (using password: NO)
private function insertToMysql()
{
include_once('connect_db.php');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection) or die('Database error -> ' . mysql_error());
//Queries
}
我尝试回显include_once并返回1.这意味着,包含了connect_db.php,但不知何故未加载常量。可能是什么问题???凭证是完美的,我验证了它们。我不是PHP的新手。
connect_db.php的内容:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '<MyPassword>');
define('DB_DATABASE', 'testdb');
?>
答案 0 :(得分:0)
删除连接处理程序
private function insertToMysql()
{
include_once('connect_db.php');
mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE) or die('Database error -> ' . mysql_error());
//Queries
}
答案 1 :(得分:0)
似乎$connection
是一个局部变量,您可以通过将其设为全局来解决此问题。
这样做。
include_once('connect_db.php');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection) or die('Database error -> ' . mysql_error());
function insertToMysql()
{
//Queries
mysql_query('Some query');
}