简体   繁体   中英

Where do I need to use backticks or quotes in my MYSQL query?

I am trying to run the following query, but I am not sure if my 's should be `s or not, $form_id = the record's column , $user_id is the primary key of the record called cf_id .

$querydate is going to be echo'd later on in the script, as it pulls the date from the record that equals to $form_id and $user_id .

$querydate = mysql_query("SELECT '$form_id' FROM email_history WHERE cf_id = '$user_id'") or die(mysql_error());

EDIT >>>>>>

After trying some of the solutions below, it seems to work ok, but instead of getting the date stored under the form name, I am getting this echo'd instead, so im not sure whats happening now : :Resource id #120 :Resource id #121 :Resource id #122 :Resource id #123

The table is setup like the followng:

[USER_ID] [FORM_ID1212212]  [FORM_ID1212112]  
 [1]      [2-1-2012]        [2-1-2012]       
 [2]      [1-1-2012]        [1-1-2012]       

You use backticks (`) for table and column names, single quotes (') for strings.

$querydate = mysql_query("SELECT `$form_id` FROM email_history WHERE cf_id = '$user_id'"); 

Backticks are only needed when your table name or column name is a MySQL reserved word... best practise is to avoid reserved words

But also consider switching to PDO and using prepared statements, or at least to mysqli rather than mysql

Best practice would be:

"SELECT `$form_id` FROM `email_history` WHERE `cf_id` = '$user_id'"

Backticks should be used around field names and table names (and DB names), and quotes should be used around values.

You should:

  1. ensure that $form_id is a legal table name, especially if it's generated from user-supplied input.

  2. use a bound parameter for $user_id

eg:

$sql = "SELECT `$userid` FROM `email_history` WHERE `cf_id` = ?"
$res = $db->query($sql, array($user_id));
while ($row = $res->fetchRow()) {
   ...
}

Back-ticks are appropriate for all table and column names. Unfortunately you can't use variable column names in a parameterised query, so you do need to construct that part of the query by hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM