Problem with query in php because of quotation marks

2

I'm having trouble with a query in php as follows, Example:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway'); 

This query works normally, but when I need to use some word that has' in the middle it causes a query problem.

Example:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','D'Agua'); 

This query already happens an error because of the word D'Agua. What is the simplest way to solve this? Note: The query is being executed in PHP.

    
asked by anonymous 07.04.2016 / 15:20

2 answers

4

The ideal, as already mentioned by @rray, is to use prepared statements .

But if you use string "single", there is already a right function for this. For example, using mysqli_ functions:

$sql='INSERT INTO Tbl(campo) VALUES ("'.mysqli_real_escape_string( $conn,"D'Agua").'");';
//ou
$sql='INSERT INTO Tbl(campo) VALUES ("'.$mysqli->real_escape_string("D'Agua").'");';


Or in PDO:

$sql = 'INSERT INTO Tbl(campo) VALUES ('. $conn->quote("D'Agua").');';

(note that quote already adds quotation marks in the string)


Obsolete, but if you are still using mysql functions in "old" applications (I do not recommend):

$sql = 'INSERT INTO Tbl(campo) VALUES ("'.mysql_escape_string("D'Agua").'");';


Here's an example with prepared statements with mysqli_ functions:

$stmt = $mysqli->prepare('INSERT INTO TBL(campo) VALUES (?)');
$stmt->bind_param('s', "D'Agua" );
$stmt->execute();

    
07.04.2016 / 18:34
-3

use the addslashes () function.

Example:

    $query=addslashes("INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
    VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','D'Agua')");
    mysql_query($query);
    
07.04.2016 / 15:31