This question already has an answer here:
I have a small problem with a PHP function that can't access a variable that was defined outside its code block and I can't see what the problem is. Redefining the variable inside the function block works fine but seems a superfluous step:
<?php
//constants for database connection
define(DB_RESOURCE, "192.168.99.67");
define(DB_USERNAME, "myUsername");
define(DB_PASSWORD, "p@ssword");
define(DB_NAME, "myDatabase");
//variable defined here so why can't function see it?
$dbConnect = mysqli_connect(DB_RESOURCE, DB_USERNAME, DB_PASSWORD, DB_NAME);
function readData($table, $column) {
$sql = "SELECT {$column} FROM {table}";
//redefining this solves the problem but why is this needed?
// $dbConnect = mysqli_connect(DB_URL, DB_USER, DB_PASS, DB_NAME);
//the $dbConnect variable is not defined and error is flagged in PHPStorm in the line below
$data = mysqli_query($dbConnect, $sql);
}
?>
Any ideas why this is happening?
Many thanks for your help,
Kw
</div>