Rocktale Rocktale - 29 days ago 7
PHP Question

variable from required_once() not defined but works with require(), why?

I'm fairly new to programming and have to make a website compatible to php7.
I don't want to change more of the code then I need to so I decided to change the old deprecated (and not working anymore)

mysql_
to the newer
mysqli_
db-connection.

So far everything works quite well but in a few scripts I have a problem with the require_once of db-connection-script it's included at the top of the script and works well but in a "function" in the same script the included db-connection-file and it's variables are not usable not even when I "include_once" it again.

But if i just "include()" it, it works again. My question is, why?
As i have understood it including a file multiple times without the "include_once" could cause problems so I really need help in understanding this issue.

index.php:

<?php
require_once('../../Connections/db.php');
mysqli_select_db($dbcon, $dbname);
$query = "SELECT x, y FROM dbtable WHERE z";


works well but within the same file:

function pruefe_datum($datum){

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
require_once('../../Connections/db.php');
$theValue = mysqli_escape_string($dbcon, $theValue);
} } }


throws:


Notice: Undefined variable: dbcon and Warning: mysqli_escape_string() expects parameter 1 to be mysqli, null given

Answer

Assuming you did not close the DB connection before this function the following should work:

function pruefe_datum($datum){
    if (!function_exists("GetSQLValueString")) {
        function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
            global $dbcon; 
            $theValue = mysqli_escape_string($dbcon, $theValue);
        }
    } 
}

It is a scope issue. The $dbcon variable doesn't exist inside the function and the second require_once is ignored and not needed.