mysqli连接的PHP函数给出错误 [英] PHP function for mysqli connection gives error

查看:98
本文介绍了mysqli连接的PHP函数给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

较新创建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) ...

Newer to creating php functions and mysql. I have function to connect to a database db_conect_nm(). This is in file db_fns.php, and contains the user and password to connect to my db. I created this to have a more secure db connection. I had it in a directory outside of public_html, and got error PHP Warning: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for user 'negoti7'@'localhost' (using password: NO) ...

在寻找解决方案时,我看到一些注释,表明该数据库用户可能没有root权限,因此我将其放在public_html的目录中,该目录与调用该程序的目录相同.我仍然遇到相同的错误.

Looking for solutions, I saw comments which indicated that perhaps this db user did not have permission from root, so I put it in a directory in public_html, same directory as program where it is being called. I still get the same error.

我已经测试了该连接而不是一个功能,并且它可以正常工作.有什么问题,为什么这不能作为功能?我真的想将其直接放置在代码中以外的地方,并使其更加安全.

I have tested the connection without being a function, and it works. What is wrong, and why is this not working as a function? I really want to put this somewhere other than in the code directly and make it more secure.

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.

I call it from nm_functions.php, db_fns.php is included there.

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

?>

有什么想法吗? 谢谢

推荐答案

可能是变量的范围吗?您是否尝试过定义要测试的函数中的变量?

Could it be the scope of the variables? Have you tried defining the variables inside the function to test?

赞:

<?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; 
}

?>

这篇关于mysqli连接的PHP函数给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆