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
https://forums.phpfreaks.com/topic/113050-dynamic-column-name-in-update-statement/
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

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.