Jump to content

Dynamic column name in UPDATE statement


silentweed

Recommended Posts

hi everyone - in context this line works fine:

 

$sql = "UPDATE odb_upload SET judge_bean ='".$_POST[$i]."' WHERE id = '".$_POST['record'.$i]."'";

 

however I want the column name to be dynamic e.g

 

$columname = "judge_bean";
$sql = "UPDATE odb_upload SET $columnname ='".$_POST[$i]."' WHERE id = '".$_POST['record'.$i]."'";

 

However the above does not work... any ideas? thanks in advance for the help!!

 

Link to comment
Share on other sites

thanks but i need to know the actual syntax for the UPDATE statement..if you have a look at my post ..you will see what i mean that is:

 

$columname = "judge_bean";
$sql = "UPDATE odb_upload SET $columnname ='".$_POST[$i]."' WHERE id = '".$_POST['record'.$i]."'";

 

the above UPDATE syntax needs to be changed...as it doesnt work

Link to comment
Share on other sites

The syntax in the "reply #2" post is correct. It did not work because you had a spelling error in the variable name. $columname is not equal to $columnname

 

When learning php, developing php code, or debugging php code, turn on full php error reporting (set error_reporting to E_ALL and set display_errors to On) to get php to help you find errors like this one.

Link to comment
Share on other sites

Also, if your variable names are two words, you should use_underscores or useCamelCaps (depending on your preference and the preference of those you share code with, I prefer underscores) so it's easier to read, and it also helps with spelling errors - $thisisnotanicevariablenameisit.

 

Also, I find enclosing variable names in {} to be much nicer on the eyes than switching in and out of strings and concatenating.

e.g.

"UPDATE odb_upload SET {$column_name} = '{$_POST[$i]}' ..."

rather than

"UPDATE odb_upload SET ".$column_name."='".$_POST[$i]."' ..."

It also means you can include array elements inside strings.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.