When to surround SQL fields with apostrophes?

I notice that when I value INSERTboth SELECTin and out of the database, I have to surround the fields with single quotes, for example:

mysql_query("INSERT INTO employees (name, age) VALUES ('$name', '$age')");

However, if I were updating the age, I would not use single quotes:

mysql_query("UPDATE employees SET age = age + 1 WHERE name = '$name'");

Also, it seems that when adding a date to the SQL database, I don't need to surround it with single quotes:

mysql_query("INSERT INTO employees (name, date) VALUES ('$name', NOW())");

In addition, when using operators such as CONCAT, this is also not necessary:

mysql_query("UPDATE employees SET name=CONCAT(name,$lastName) WHERE id='$id'");

Maybe I’m just coding poorly, but it seems like I remember if I didn’t surround the single-quoted box when inserting and selecting its operation.

+3
source share
4 answers

, , text, char, varchar .. , date, time, datetime.

, int, bigint, decimal .. SQL-, now(), current_date, .

+3

"" php- ($ age), MySQL. ( ), , select insert.

, php , , ​​ . php , .

SELECT * from something where age = $age;

- $age , , , , ​​ , "where age = ;"

SELECT * from something where age = '$age';

- $age , , ​​ , " age = '"; - .

SQL- - , .

+3

, :

  • sql: SELECT, UPDATE, WHERE, NULL,... ( , )
  • (sql) : + -/*.() ..
  • sql: NOW(), CONCAT(),...
  • , : , , , ,... , `field`, , . ORDER

, , , "" "", 1, 10, 19, 1.005. NULL - , " ".

, .

, .

+1

String values ​​(including single characters) must be enclosed in single quotes. This includes date constants represented using strings. Numeric values ​​do not need quotation marks.

0
source

All Articles