Forum Moderators: coopster

Message Too Old, No Replies

trying to escape an apostrophe

php query error

         

hal12b

6:40 pm on Mar 26, 2022 (gmt 0)

10+ Year Member



I have a dynamic drop down that prepopulates from a MySQL database. Of the 600 or so options, a few have an apostrophe, like "Joe's Car". The user is able to select an item from this list which then does a query to pull info for this selection. Obviously this apostrophe is causing a problem and breaks the query if an option is selected like "Joe's Car".

this is the line of code
$query1 = "SELECT * from tblCars WHERE CUSTOMER = '$customer'";

The only thing I have been able to find says to do this -->

$customer = mysql_real_escape_string('$customer');
$query1 = "SELECT * from tblCars WHERE CUSTOMER = '$customer'";



However, it doesn't work, Any input is appreciated.

phranque

7:45 pm on Mar 26, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



replace each single-quote character with a doubled single-quote character:
''

phranque

10:16 pm on Mar 26, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



here is the MySQL documentation:
There are several ways to include quote characters within a string:
  • A ' inside a string quoted with ' may be written as ''.
  • ...

source: String Literals [dev.mysql.com]

lucy24

4:17 am on Mar 27, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Are curly apostrophes ’ an option, or are you constrained to ASCII?

hal12b

1:52 pm on Mar 27, 2022 (gmt 0)

10+ Year Member



Lucy24 that was a good idea. I replaced them all with the curly apostrophes in the database. There were only 14 instances out of 700. The next time I do this import I guess the best thing to do is a find and replace in excel before the import.

w3dk

10:30 pm on Mar 27, 2022 (gmt 0)

10+ Year Member Top Contributors Of The Month




$customer = mysql_real_escape_string('$customer');


$customer should not be surrounded in single quotes. You also need an active DB connection. And, unless you are on <PHP7 then you need to be using the MySQLi functions instead.

For example, you should be using the following instead:


$quotedCustomer = mysqli_real_escape_string($conn, $customer);


Otherwise this should "work", mysqli_real_escape_string() (and the deprecated/removed mysql_real_escape_string()) backslash-escape any single quote characters.


Are curly apostrophes ’ an option ...


Users don't usually type curly apostrophes though.

lucy24

4:35 am on Mar 28, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Users don't usually type curly apostrophes

OP said “dropdown”, meaning that the user is selecting from a pre-set list.