0

I can't connect to a db into a function: the db connection is lost into the function. error : mysqli_query() expects parameter 1 to be mysqli, null given

$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');
}

thank you in advance

1 Answers1

1

You can rewrite your function slightly to access $dbcon as a global var:

function news() {

    global $dbcon;

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

}

or pass it as an argument to news():

function news($dbcon) {

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

}