Вопрос

I understand that mysqli_real_escape_string() function is used to prevent SQL injection, but I don't know why this function is designed to take two parameters instead of only one? I understand $_POST["firstname"] is the input String to get escaped using this function but why the $connection is also needed as the first parameter? I am a starting php learner, sorry if this question doesn't make too much sense.

// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
var_dump($firstname);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

if (!mysqli_query($con,$sql)) {
   die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>
Это было полезно?

Решение

As shown in the PHP manual:

The procedural style for this function requires a mysqli instance, in other words, a connection to the database previously created (This may be oversimplifying):

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

In order to call this function without the first parameter you need to instanciate the mysqli class, hence providing the function with the connection without really adding any other parameter. This is how the class is instanciated:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

And this would be the way to call the function in an object oriented manner:

$string = $mysqli->real_escape_string($string);

Hope this clarifies a bit your question.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top