Drupal模块用于将csv文件插入mysql数据库

时间:2017-04-30 16:52:49

标签: php mysql csv drupal drupal-7

我尝试运行此代码,但是当我按下导入时,我没有收到错误消息。当我进入mysql数据库时,每一行都是空白的,我有大约3500行..有人可以告诉我该怎么做..?这是一个代码:

    <?php

/**
 * Implements hook_permission()
 */
function module_name_permission() {
  return array(
    'administer uploader' => array(
      'title' => t('Administer Uploader'),
      'description' => t('Allow the following roles to upload csv files to the server.'),
    ),
  );
}

/**
 * Implements hook_menu()
 */
function module_name_menu() {
  $items['file-uploader'] = array(
    'title' => 'Upload a File',
    'type' => MENU_CALLBACK,
    'description' => 'Import a csv',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_name_import_form'),
    'access arguments' => array('administer uploader'),
  );
  return $items;
}

/**
 * Builds a form that will allow users to upload csv files
 * 
 * @see
 *   hook_menu()
 */
function module_name_import_form($form, $form_state) {
  $form['notes'] = array(
    '#type' => 'markup',
    '#markup' => '<div class="import-notes">A few notes when uploading. <ul><li>Make sure the file is in a .csv format.</li><li>Columns should be in *this* order</li><li>Be sure to click the "Upload" button when you select a csv.</li></ul></div>',
    '#upload_location' => 'public://tmp/',
  );
  $form['import'] = array(
    '#title' => t('Import'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded csv will be imported and temporarily saved.'),
    '#upload_location' => 'public://tmp/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('csv'),
    ),
  );
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Import'),
  );
  return $form;
}

/**
 * Submit handler for module_name_import_form()
 */
function module_name_import_form_submit($form, $form_state) {


  $file = $_FILES ['file']['tmp_name'];

    $handle = fopen($file, "r");

    while(($fileop = fgetcsv($handle, 100, ",")) !==false)
    {

      $firstname = $fileop[0];
      $lastname = $fileop[1];
      $email= $fileop[2];



       db_query("INSERT INTO csvupload (first_name, last_name, email) VALUES ('$firstname', '$lastname', '$email') ");


  }

  fclose($handle);
}

还有简单的csv文件:

asd,asd,@yahoo
asd,asd,@gmail
asd,asd,@hotmail
asd,asd,@gmail

1 个答案:

答案 0 :(得分:0)

$_FILES ['file']['tmp_name']是否会为您提供上传的文件?使用正确的托管文件处理方式更新了代码。

/**
 * Submit handler for def_import_form()
 */

function def_import_form_submit(&$form, &$form_state) {

  $temp = file_load($form_state['values']['import']);
  $file = file_create_url($temp->uri);

  $handle = fopen($file, "r");

  while(($fileop = fgetcsv($handle, 100, ",")) !==false)
  {
    $firstname = $fileop[0];
    $lastname = $fileop[1];
    $email= $fileop[2];

    /** add values to db **/
  }

  fclose($handle);
}