How to insert into a database with special characters?

5

I am doing the following INSERT :

$result = mysql_query("INSERT INTO tbl_livro VALUES (NULL, '$titulo', '$autor_livro')");

What happens is that there are authors who have names with special characters, for example: O'Reilly Media, Inc.

What happens is that ' conflicts with insertion.

Is there any way to ignore the special characters that are inside the $autor_livro variable? The goal is to insert with special characters.

Note: I know I should use mysqli or PDO but in this example it has to be mysql .

    
asked by anonymous 29.01.2015 / 12:08

1 answer

4

Special characters must be escaped in your query.

In your case, use mysql_real_escape_string

$titulo = mysql_real_escape_string($titulo);
$autor_livro = mysql_real_escape_string($autor_livro);
$result = mysql_query("INSERT INTO tbl_livro VALUES (NULL, '$titulo', '$autor_livro')");

Note: This is a case worth using Mysqli or PDO . Both support prepared statements and you would not have that kind of problems inserting parameters into your query.

Example of using prepared statements with PDO:

$stmt = $pdo->prepare("INSERT INTO tbl_livro VALUES (NULL, :titulo, :autor_livro)");
$stmt->bindParam(':titulo', $titulo);
$stmt->bindParam(':autor_livro', $autor_livro);

$stmt->execute();
    
29.01.2015 / 12:12