简体   繁体   中英

Add special character in PHP

My database don't store $title with particular characters. What can I do? Below my php code:

    <?php
require "init.php";
$user_name = $_POST["user_name"];
$title = $_POST["title"];
$author = $_POST["author"];
$urlImage = $_POST["urlImage"];

preg_match("/^[\p{L}\p{N} '.-]+$/", $title);
$sql_query = "insert into user_info_book values('$user_name', '$title', '$author', '$urlImage');";
?>

Thank you in advance

Special characters can break your SQL query, so to deal with that, either use prepared statements or use the mysqli_real_escape_string() function.

The mysqli_real_escape_string() function requires two parameters, the first one being the connection object, the second being the string to be escaped, an example below

$title = mysqli_real_escape_string($conn, $title);

However, a better approach would be to use prepared statements instead. An example of this is given below

if ($stmt = $conn->prepare("INSERT INTO user_info_book VALUES (?, ?, ?, ?)")) {
    $stmt->bind_param("ssss", $user_name, $title, $author, $urlImage);
    $stmt->execute();
    $stmt->close();
} else {
    // echo mysqli_error($DB_H); // Errors should only be shown in development
}

Everywhere in the code, $conn is the connection object you already created.

$title = mysql_real_escape_string($title);

mysql_real_escape_string()转义字符串中的特殊字符以用于SQL语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM