Question

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]       
Was it helpful?

Solution

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

OTHER TIPS

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

e.g.:

$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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top