GetSQLValueString / mysqli_real_escape_string / Notice: Undefined variable: mysqli

1

I'm trying to convert a function to Mysqli, for use with PHP7.1. I'm having difficulty with mysqli_real_escape_string , and mysqli_escape_string .

Error:

  

Notice: Undefined variable: mysqli in   config.php on line 16

     

Warning: mysqli_escape_string () expects parameter 1 to be mysqli, null given in > config.php on line 16

FILE CONFIG.PHP

require_once('Connections/conexao.php');

$mysqli = new mysqli($hostname_conexao,$username_conexao,$password_conexao,$database_conexao); if($mysqli->connect_error){echo "Erro";exit();}

if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
    {
        if (PHP_VERSION < 6) {
            $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
        }

        $theValue = function_exists("mysql_real_escape_string") ? mysqli_real_escape_string($mysqli, $theValue) : mysqli_escape_string($mysqli, $theValue);

        switch ($theType) {
            case "text":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "long":
            case "int":
                $theValue = ($theValue != "") ? intval($theValue) : "NULL";
                break;
            case "double":
                $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
                break;
            case "date":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "defined":
                $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
                break;
        }
        return $theValue;
    }
}

What do I need to do?

    
asked by anonymous 15.06.2017 / 19:00

2 answers

1

The problem is that the GetSQLValueString function is trying to access a variable that is outside of it, ie the variable is in a different scope , so adjust it to use global like this:

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{

     global $mysqli;

You can also try other approaches like OOP, but this is another story, it's just a suggestion.

    
15.06.2017 / 19:26
1

Change mysql to mysqli , I believe it's a misspelling of yours.

It would look like this:

$theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($mysqli, $theValue) : mysqli_escape_string($mysqli, $theValue);

In object-oriented mode, it asks for only one parameter, it would look like this:

$theValue = function_exists("mysqli_real_escape_string") ? mysqli->real_escape_string($theValue) : mysqli->escape_string($theValue);
    
15.06.2017 / 19:06