Funkce PHP mysqli real_escape_string().
Příklad - Objektově orientovaný styl
Escape speciálních znaků v řetězcích:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " .
$mysqli -> connect_error;
exit();
}
// Escape special characters, if any
$firstname = $mysqli -> real_escape_string($_POST['firstname']);
$lastname = $mysqli -> real_escape_string($_POST['lastname']);
$age =
$mysqli -> real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname', '$lastname', '$age')";
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
$mysqli -> close();
?>
Podívejte se na příklad procedurálního stylu dole.
Definice a použití
Funkce real_escape_string() / mysqli_real_escape_string() escapuje speciální znaky v řetězci pro použití v dotazu SQL, přičemž bere v úvahu aktuální znakovou sadu připojení.
Tato funkce se používá k vytvoření platného řetězce SQL, který lze použít v příkazu SQL. Předpokládejme, že máme následující kód:
<?php
$lastname = "D'Ore";
$sql="INSERT INTO Persons (LastName) VALUES ('$lastname')";
// This query will fail, cause we didn't escape $lastname
if (!$mysqli -> query($sql)) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}
?>
Syntax
Objektově orientovaný styl:
$mysqli ->
real_escape_string(escapestring)
Styl postupu:
mysqli_real_escape_string(connection, escapestring)
Hodnoty parametrů
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
escapestring | Required. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z. |
Technické údaje
Návratová hodnota: | Vrátí uniklý řetězec |
---|---|
Verze PHP: | 5+ |
Příklad - Procedurální styl
Escape speciálních znaků v řetězcích:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Escape special characters, if any
$firstname = mysqli_real_escape_string($con, $_POST['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))
{
printf("%d Row inserted.\n", mysqli_affected_rows($con));
}
mysqli_close($con);
?>
❮ Reference PHP MySQLi