John Davidson

sql - When to use single quotes, double quotes, and backticks in MySQL

0 comments
Message:


I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.


Example:


$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';

Also, in the above example, consider that table, col1, val1, etc. may be variables.


What is the standard for this? What do you do?



My Answer:
In MySQL, the standard practice is to use single quotes for string literals and backticks for table and column names that may contain special characters or be MySQL reserved keywords. Double quotes are not typically used in MySQL queries.

So in your example, the query should be written as:

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'val1', 'val2')";

This way, you are following the standard practice and ensuring that your queries will work correctly in MySQL. Remember to always sanitize and validate user input to prevent SQL injection attacks.

Rate this post

5 of 5 based on 2675 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us