Can columname be variable in mysql update syntax?

I want to update whatever column value in table. If I echo $q it gets the variables but it won't update and won't echo mysql error. So how can I do it?

 function up($name, $value, $id){     

 $q='UPDATE Table SET '.$name.'='.$value.' WHERE ID="'.$id.'"';
     $r=mysql_query($q, $conn);
     if(!$r){
     echo('Could not update data: ' . mysql_error());
   } else{ echo "Updated data successfully\n"; } 
 }

Answers


The variable $q is interpreted before being sent to MySQL so you can have the column names, and everything else for that matter, be dynamic at runtime. The final value of that string is what MySQL will see.

If you're row is not updating and you're not getting an error then your query is incorrect in some manner. Make sure all of your conditions in your WHERE clause are correct. And a better way to see if your rows were affected is to use mysql_affected_rows().

else{ echo "Updated data successfully\n"; } 

should be

else if(mysql_affected_rows() !== 0){ echo "Updated data successfully\n"; } 

FYI, you should consider migrating away from mysql_* functions since they will soon be going away.


Need Your Help

ios horizontal auto layout with buttons

ios objective-c iphone layout

i want to learn auto layout and apply it in my project. i have a UIViewController which looks like this