Jump to content
Larry Ullman's Book Forums

How To Make Database Connection Inside A Function


Recommended Posts

I have following 3 files : The database connection ($dbc) never gets available inside the function. I tried to make database connection directly inside the datacheck.php file, then also it shows error: undefined variable dbc...I tried to print_r($dbc) inside the function. It also shows error: undefined variable dbc....When I print outside of the function, it shows object details with error 0.

 

For testing purposes, I kept all files in the same folder. So I'm sure file paths are correct.

 

dbconfig.php

DEFINE ('DB_USER', 'xmxmx');

DEFINE ('DB_PASSWORD', 'mxmxmx');

DEFINE('DB_HOST', 'mmsmsms');

DEFINE('DB_NAME', 'mmxmxm');

 

//Make the connection:

 

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

 

if(!$dbc)

{

trigger_error('Could not connect to MySQL: '. mysqli_connect_error());

}

 

//IDentify MySql the encoding to be used.

 

mysqli_set_charset($dbc, 'utf8_general_ci');

 

 

datacheck.php

require_once('dbconfig.php');

 

function checkUser($uid) {

$query = "SELECT * FROM users1 WHERE oauth_uid = '{$uid}'";

$result = mysqli_query($dbc, $query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysqli_error($dbc));

$row = mysqli_fetch_row($result);

if(!empty($row)) {

echo "USEr is present";

}

return $row;

 

}

 

test.php

require_once('datacheck.php');

$uid = '12345';

checkUser($uid);

Link to comment
Share on other sites

 Share

×
×
  • Create New...