mysql语句如何插入含单引号或反斜杠的值详解

网络编程 2025-03-23 19:55www.168986.cn编程入门

让我们看一下一个简单的MySQL表创建示例:

```sql

CREATE TABLE `activity` (

`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',

`title` varchar(255) NOT NULL COMMENT '活动标题',

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='活动表';

```

```php

$servername = "数据库服务器名";

$port = 3306;

$username = "用户名";

$password = "密码";

$dbname = "数据库名";

// 创建连接

$conn = new mysqli($servername, $username, $password, $dbname, $port);

// 检测连接

if ($conn->connect_error) {

die("连接失败: " . $conn->connect_error);

}

$item['title'] = 'happy valentine\'s day!'; // 使用转义后的字符串

$sql = sprintf("INSERT INTO activity (title) VALUES ('%s')", mysqli_real_escape_string($conn, $item['title']));

var_dump($sql); // 查看生成的SQL语句

if ($conn->query($sql) === TRUE) {

} else {

}

$conn->close();

```

示例代码如下:

```php

$item['title'] = json_encode([

'balbalbla' => '中文'

]);

$sql = sprintf("INSERT INTO activity (title) VALUES ('%s');", mysqli_real_escape_string($conn, $item['title']));

```

上一篇:DropDownList添加客户端下拉事件操作 下一篇:没有了

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by