更新创建php函数和mysql。我有连接数据库db_conect_nm()的功能。这是在文件db_fns.php中,包含连接到我的数据库的用户和密码。我创建它以获得更安全的数据库连接。我把它放在public_html之外的目录中,并收到错误PHP Warning: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for user 'negoti7'@'localhost' (using password: NO) ...
寻找解决方案,我看到的评论表明,这个db用户可能没有root用户的权限,所以我将它放在public_html的目录中,与调用它的程序目录相同。我仍然得到同样的错误。
我已经测试了连接而不是一个功能,它可以工作。有什么不对,为什么这不起作用?我真的想把它放在除代码之外的其他地方并使它更安全。
db_fns.php内容
<?php
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
?>
我从nm_functions.php调用它,db_fns.php包含在那里。
nm_functions.php
<?php require_once('sanitizedpathto/db_fns.php');
......some code
$conn_nm = db_connect_nm();
$result_sub = $conn_nm->query("select * from subscribers where uname='$username'");
.... more code
?>
有什么想法吗? 感谢
答案 0 :(得分:1)
它可能是变量的范围吗?您是否尝试在函数内定义要测试的变量?
像这样:
<?php
// db connect to nm database
function db_connect_nm()
{
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
&GT;
答案 1 :(得分:0)
你是:
默认情况下,在函数内部声明的函数不在函数内部可见。
关于这一点,您应该阅读手册的Variable scope部分。
两种可能的解决方案:
在第一种情况下,您的函数将如下所示:
// db connect to nm database
function db_connect_nm()
{
// Make these outside variables visible from inside the function
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
而且,在第二种情况下,你首先要define
常数:
define('DB_HOST', 'localhost');
define('DB_DBNAME', 'myname_databasename');
define('DB_USER', 'myname_dbusername');
define('DB_PASSWORD', 'password');
然后,使用这些常量:
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DBNAME);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
第二个解决方案可能比第一个更干净; - )
答案 2 :(得分:0)
您的连接变量不在连接函数范围内。您需要将它们作为参数传递给函数(最好)或使用里面的global
关键字来引用它们:
function db_connect_nm($host, $nm_user, $nm_pword, $nm_name)
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}
替代,不是首选:
function db_connect_nm()
{
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}