0

When I'm trying to save a node using batch processing, I'm getting this error:

PDOException: in drupal_write_record() (line 7383 of C:\wamp64\www\drupal7\includes\common.inc).

Here is my complete code:

function custom_node_import_form_submit($form, &$form_state) {
  $csvFile = file_load($form_state['values']['csv_file']);
  $csvFilepath = drupal_realpath($csvFile->uri);
  $file = fopen($csvFilepath, "r");

  $batch = array(
    'operations' => array(),
    'finished' => 'node_import_finished',
    'title' => t('Node import'),
    'init_message' => t('Importing is starting...'),
    'progress_message' => t('Imported @current out of @total.'),
    'error_message' => t('Node importer has encountered an error.')
  );

  fgetcsv($file, 0, ",");
  while($line = fgetcsv($file)) {
    $batch['operations'][] = array('node_import_progress', array(array_map('base64_encode', $line)));
  }

  batch_set($batch);
  batch_process('admin/node/custom-node-import');
  fclose($file);
}

function node_import_progress($line, &$context) {
  $line = array_map('base64_decode', $line);
  saveNode($line);
  $context['message'] = t('Importing %title', array('%title' => $line[0]));
}

function node_import_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Node importing is complete!'));
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}
function saveNode($param = []) {
  global $user;

  $node = new stdClass();
  $node->title = $param[0];
  $node->type = "article";
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid; 
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;      
  $node->body[$node->language][]['value'] = $param[3];

  $node = node_submit($node);
  node_save($node);
}

I have debugged and found that the line which gives this error is the last line where the node is getting saved. i.e node_save($node);

1 Answer 1

1

The issue was with the non-English characters in the CSV file like ö, ä etc

So the solution was to use utf8_encode() for the values:

$node->title = utf8_encode($param[0]);
$node->body[$node->language][]['value'] = utf8_encode($param[3]);

Hope it helps somebody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.