将db连接到函数

时间:2016-09-07 15:25:49

标签: php database connection

我无法将db连接到函数中:db连接会丢失到函数中。 错误:mysqli_query()期望参数1为mysqli,给定

为null
$dbcon = mysqli_connect($db_server, $db_user, $db_passwd);

/* check connection */
if ($dbcon->connect_errno) {
  printf("Connect failed: %s\n", $dbcon->connect_error);
  exit();
}

mysqli_select_db($dbcon,$db_name);

function news()
{

    $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news');
}

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以稍微重写您的函数以访问$ dbcon作为全局变量:

function news() {

    global $dbcon;

    $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news');

}

或将其作为参数传递给news():

function news($dbcon) {

   $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news');

}