Error: "mysqli_real_escape_string() expects parameter 1 to be mysqli, null given"

StackOverflow https://stackoverflow.com/questions/23378453

  •  12-07-2023
  •  | 
  •  

문제

I'm getting an error when I try to use the function below.

require_once("connection.php");

function check_max_field_lengths($field_length_array) {
    $field_errors = array();
    foreach($field_length_array as $fieldname => $maxlength ) {
        if (strlen(trim(mysqli_real_escape_string($connection, $_POST[$fieldname]))) > $maxlength) { $field_errors[] = $fieldname;
        }
    }
    return $field_errors;
}

It says:

mysqli_real_escape_string() expects parameter 1 to be mysqli, null given

But I've already defined $connection in the connection.php file like so:

require("constants.php");
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME) or die("Database connection failed: " . mysqli_error($connection));

$connection works fine in my other uses, but not here. Any idea why?

도움이 되었습니까?

해결책

Simply pass the connection to your function

function check_max_field_lengths($field_length_array, $connection) {
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top