Error while creating a node with file attachment through custom PHP code I need to programmaticly create  a node in Drupal 7 i followed availible tutorials and came up with this code:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


$md5 = md5(strtotime("now"));

$field_customer_name = 'NAthtn';
$field_customer_email = "something@gmail.com";
$field_downloads_count_left = '11';

$filename = 'file123.zip';
$filepath = 'sites/default/files/private/file123.zip';

// Create managed File object and associate with file field.
$file = new StdClass();
$file-&gt;uid = 1;
$file-&gt;uri = $filepath;
$file-&gt;filename = $filename;
$file-&gt;filemime = file_get_mimetype($file-&gt;uri);
$file-&gt;status = 1;  
$file = file_copy($file, 'public://', FILE_EXISTS_REPLACE);

$node = new stdClass();
$node-&gt;type = 'download';
node_object_prepare($node);

$node-&gt;title    = $md5;
$node-&gt;language = LANGUAGE_NONE;

$node-&gt;field_customer_name[$node-&gt;language][0]['value'] = $field_customer_name;
$node-&gt;field_customer_email[$node-&gt;language][0]['value'] = $field_customer_email;
$node-&gt;field_downloads_count_left[$node-&gt;language][0]['value'] = $field_downloads_count_left;
$node-&gt;field_file[$node-&gt;language][0]['value'] = (array)$file;

$path = $md5;
$node-&gt;path = array('alias' =&gt; $path);

node_save($node);


I am getting the following error in the log:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 51 [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 664 of /home/content/16/5470416/html/download/includes/file.inc).
replace

$node-&gt;field_file[$node-&gt;language][0]['value'] = (array)$file;

with

$node-&gt;field_file[$node-&gt;language][] = (array)$file;

Also, add $node-&gt;validated = TRUE; before node_save($node);