PHP function for mysqli connection gives error

一个人想着一个人 提交于 2019-12-02 05:08:19

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

Like this:

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

?>

You are :

  • first, declaring some variables, outside of any functions
  • then, trying to use those variables from inside a function.

Variables declared outside of a function are not, by default, visible from inside that function.

About that, you should read the Variable scope section of the manual.


Two possible solutions :

  • Use the global keyword, to import those variables into your function -- making them visible
  • Or define constants, instead of variables -- which makes sense, for configuration values.


In the first case, your function would look like this :

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


And, in the second case, you'd first define the constants :

define('DB_HOST', 'localhost');
define('DB_DBNAME', 'myname_databasename');
define('DB_USER', 'myname_dbusername');
define('DB_PASSWORD', 'password');

And, then, use those constants :

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

This second solution is probably more clean than the first one ;-)

Your connection variables are not scoped inside the connection function. You either need to pass them as parameters to the function (preferable) or use the global keyword inside to reference them:

function db_connect_nm($host, $nm_user, $nm_pword, $nm_name)
{
  $nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);

  //etc...
}

Alternate, not preferred:

function db_connect_nm()
{
  global $host, $nm_user, $nm_pword, $nm_name;
  $nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);

  //etc...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!