Question

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?

Was it helpful?

Solution

Simply pass the connection to your function

function check_max_field_lengths($field_length_array, $connection) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top