Drupal 7 update field programatically and generate field names
Your problem is that below code does not work as you probably expect. 

$node-&gt;$fieldname['und'][0]['value'] = $row-&gt;$fieldname;


You expect this to work like this:

$fieldname = 'name'; 
$node-&gt;name['und'][0]['value'] = $row-&gt;name;


but PHP will probably do something like this:

$fieldname = 'name'; 
$fieldname['und'][0]['value'] = $row-&gt;name;
$node-&gt;$row-&gt;name;


Instead, try to wrap your variable name in curly brackets to have it replaced first:

$node-&gt;{$fieldname}['und'][0]['value'] = $row-&gt;$fieldname;