Home >Backend Development >PHP Tutorial >Three PHP functions and two options to prevent SQL injection

Three PHP functions and two options to prevent SQL injection

angryTom
angryTomforward
2019-10-16 10:23:392774browse

Three PHP functions and two options to prevent SQL injection

Three functions:

1. addslashes($string): Use backslashes to quote special characters in the string ' " \

$username=addslashes($username);

2. mysql_escape_string($string): Use backslash to escape special characters in the string for mysql_query() query.

$username=mysql_escape_string($username);

3. mysql_real_escape_string($string): Escape special characters in the string used in the SQL statement, and taking into account the current character set of the connection, you need to ensure that the current connection state can be used to use this function, otherwise A warning will be reported. There are two options of not escaping % and _

$username=mysql_real_escape_string($username);

:

1. Use PDO

$stmt = $pdo->prepare('SELECT * FROM user WHERE name = :name');
$stmt->execute(array(':name' => $name));
foreach ($stmt as $row) {
// do something with $row
}

2. Use mysqli

$stmt = $dbConnection->prepare('SELECT * FROM user WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Three PHP functions and two options to prevent SQL injection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.phplaozhang.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more