【问题标题】:mysqli_connect in a function throws error函数中的 mysqli_connect 引发错误
【发布时间】:2015-04-26 14:35:13
【问题描述】:

我确定这个问题很容易回答,但我不明白。 当我尝试连接一个函数时,它会抛出一个“拒绝用户访问'@'localhost'”错误。看起来数组在数组中不可用,因为错误说我没有输入用户名和密码。

代码是:

$config["mysql_host"]   = "localhost";
$config["mysql_user"]   = "myusername";
$config["mysql_pass"]   = "mypass";
$config["db_name"]      = "mydb_name";
$config["event_tname"]  = "tablename";


function get_events(){ 
        $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database

        $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query

        $result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute

        while($all_events = mysqli_fetch_assoc($result)){  //fetch and just print it
            foreach($all_events as $key => $val)
              echo($val." | ");
        }

        mysqli_free_result($result);} //END -- clear $result
events(); //just an example: call the function

我必须在阵列上更改什么?

问候, 弗朗茨

【问题讨论】:

标签: php mysql function mysqli


【解决方案1】:

只需在你的函数中添加global $config;

function get_events(){

   global $config;

        $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database

        $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query

        $result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());

        while($all_events = mysqli_fetch_assoc($result)){  //fetch and just print it
            foreach($all_events as $key => $val)
              echo($val." | ");
        }

        mysqli_free_result($result);} //END -- clear $result
get_events(); //ju

或将配置参数传递给函数

function get_events($config){ 

        $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database

        $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query

        $result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());

        while($all_events = mysqli_fetch_assoc($result)){  //fetch and just print it
            foreach($all_events as $key => $val)
              echo($val." | ");
        }

        mysqli_free_result($result);} //END -- clear $result
get_events($config); //ju

【讨论】:

    【解决方案2】:

    首先你应该考虑使用面向对象的mysqli。没有理由再使用程序风格了。

    其次,全局 PHP 变量在函数内部不可用,因此您需要将数组传递给函数,如另一个答案中所述。

    有关 PHP 变量范围的更多信息,请参阅 this article

    恕我直言,最好的解决方案是为您的应用程序使用一个类并将配置存储为私有属性。然后该类的方法将可以访问这些属性。

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 2017-01-25
      • 2019-09-24
      相关资源
      最近更新 更多