Home >Backend Development >PHP Problem >How to escape special characters in mysql in php

How to escape special characters in mysql in php

藏色散人
藏色散人Original
2020-11-18 09:19:312902browse

In PHP, you can use the mysqli_real_escape_string function to escape special characters in strings used in mysql. The syntax is "mysqli_real_escape_string(connection,escapestring);".

How to escape special characters in mysql in php

The operating environment of this tutorial: windows10 system, php5.6. This article is applicable to all brands of computers.

Recommended: "PHP Video Tutorial"

PHP mysqli_real_escape_string() function

Definition and usage

mysqli_real_escape_string() function conversion Defines special characters in strings used in SQL statements.

Syntax

mysqli_real_escape_string(connection,escapestring);

Parameters

connection required. Specifies the MySQL connection to use.

escapestring Required. The string to escape. The encoded characters are NUL (ASCII 0), \n, \r, \, ', " and Control-Z.

Technical Details

Return Value: Returns the escaped string .

PHP Version: 5

Escape special characters in string:

<?php 
// 假定数据库用户名:root,密码:123456,数据库:RUNOOB 
$con=mysqli_connect("localhost","root","123456","RUNOOB"); 
if (mysqli_connect_errno($con)) 
{ 
    echo "连接 MySQL 失败: " . mysqli_connect_error(); 
} 

mysqli_query($con,"CREATE TABLE websites2 LIKE websites");

$newname="菜鸟&#39;教程";

// 没有转义 $newname 中特殊字符,执行失败
mysqli_query($con,"INSERT into websites2 (name) VALUES (&#39;$newname&#39;)");

// 转义特殊字符
$newpers=mysqli_real_escape_string($con,$newname);

// 转义后插入,执行成功
mysqli_query($con,"INSERT into websites2 (name) VALUES (&#39;$newpers&#39;)");

mysqli_close($con);
?>

The above is the detailed content of How to escape special characters in mysql in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to write php arrayNext article:How to write php array