0

I am adding value that start with $ symbol in sql where clause. I execute the query in php.

worked - when wrap $n in double quote and whole query in single quote

$query= 'SELECT * FROM a
          WHERE n="$n" '

not worked - wrap $n in single quote and whole query in double quote

$query= "SELECT * FROM a
          WHERE n='$n' "

Why is it so? Thanks in advance.

Premlatha
  • 1,676
  • 2
  • 20
  • 40
  • 1
    Does this answer your question? [Escaping single quote in PHP when inserting into MySQL](https://stackoverflow.com/questions/2687866/escaping-single-quote-in-php-when-inserting-into-mysql) – BhAvik Gajjar Dec 11 '19 at 07:16
  • i would suggest to you to use curly bracket and you dont need to worry about single or double quotes. `"SELECT * FROM a WHERE n='{$n}'"; "SELECT * FROM a WHERE n='{$n}'"` – Zeljka Dec 11 '19 at 07:21
  • @BhAvikGajjar , not really answer my question. @Zeljka,I tried `n='{$n}'` and `n={$n}`. Not work for me. – Premlatha Dec 11 '19 at 07:36
  • 1
    Using prepared statements will solve this and a few other problems! – Nigel Ren Dec 11 '19 at 07:38

2 Answers2

1

The value of $n parsed as string in below query because the whole query enclosed with single quote:

$query= 'SELECT * FROM a WHERE n="$n"'

But when you enclose the whole query with double quote: $n will be parsed as variable correctly.

$query= "SELECT * FROM a WHERE n='$n'"
Akam
  • 1,089
  • 16
  • 24
1

Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.

Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren’t used in SQL, but that can vary from database to database

In this case double quotes act as a variable so its working.

$query= 'SELECT * FROM a WHERE n="$n"'

Double quotes "" PHP will search every string for variables.

Ramki
  • 452
  • 2
  • 16