My php function does not recognize a variable defined in another php file that is included in within the same file. dbconnect.php makes a database connect. add_user.php has the add_user function which uses that database connection $dbco. I get an error message saying that $dbco is not defined for this function call: mysql_select_db("luxcal", $dbco); This must be something very obvious, but I don’t know what is happening.
dbconnect.php
<?php
$dbco = mysql_connect("localhost","myuser","mypassword");
if (!$dbco)
{
die('Could not connect: ' . mysql_error());
}
?>
add_user.php
<?php include("dbconnect.php"); ?>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
function add_user($username, $email, $password_text, $copasswd_text) {
$password = md5($password_text);
$copasswd = md5($password_text);
$privPost = 1; // 3: max.
$privSedit = 0;
mysql_select_db("luxcal", $dbco);
$q_add_user = "INSERT INTO users (`user_name`, `email`, `password`) VALUES ( '".mysql_real_escape_string($username)."', '".mysql_real_escape_string($email)."', '$password' )";
$r_add_user = mysql_query($q_add_user);
return;
}
echo add_user(trim($_REQUEST['uname']), trim($_REQUEST['uemail']), trim($_REQUEST['upass']), trim($_REQUEST['cpass']));
?>
The variable
$dbcois not available in the functionadd_userbecause it is not in the variable scope of the function.You can access it by adding
global $dbco;inside theadd_userfunction to make it available, or you can use$GLOBALS['dbco']instead.Try:
Variables defined outside of functions are not available inside the function unless you pass them in or use
global. Similarly, a variable defined in a function is not available outside the function (and is freed when the function returns).