How to insert into a database with special characters?

Asked

Viewed 1,390 times

5

Here’s what I’m doing 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 the ' makes conflict in insertion.

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

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

1 answer

4


It is necessary to escape the special characters 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')");

Except: This is a case worth much more using Mysqli or PDO. Both bear Prepared statements and you would not have this kind of problems when entering parameters in your query.

Example of the use of 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();
  • AP already made the reservation in the question.

  • @Jorgeb. I’ll include an extra example of how Prepared statements can help our life if someone sees the question in the future.

  • but my goal is to insert with the special characters, the mysql_real_escape_string allows this?

  • @pc_oc yes, that’s exactly what this function does.

  • thanks @gmsantos. Unfortunately in this project I have to use mysql and not PDO. thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.