2017-12-28 3 views
0

좋아요. 문제는 지금 제가 직면 한 방법이 exec() function을 사용하여 SQL 명령으로 데이터를 전달하는 방법을 이해하지 못한다는 것입니다.PHP 2 차원 배열을 1 차원 배열을 SQL 테이블에 추가 할 때

온라인 코드 57에서 implode(',',$row)을 사용해 보았습니다. 나는 또한 serialize($row)을 사용해 보았고, 다음 2 줄처럼 따옴표를 써 봤는데, 모든 매개 변수와 값을 수동으로 제공하려했지만 수동으로 실행했지만 가져온 CSV 파일의 모든 행에 100 개가 넘는 항목이있을 수 있으므로 비현실적이었습니다. 누군가가 나에게 어떻게 보여줄 수 있다면이 일을하는 더 좋은 방법이 있어야하고 이드의 사랑이 있어야합니다. 입니다 발생

<?php 
    /* DISCLAIMER: I, the creator of this script am in no way responsible for any damage or data loss said script may cause directly or indirectly to the used databases, servers, clients and/or devices it may be run on. ANY and ALL responsibility for issues pertaining to the use of this script falls to the person that requested it be created. By using this script you confirm that you have read, fully understand and fully agree to this disclaimer */ 
    /* This script has no input sanitization which means that if someone uploads a csv with any php and possibly SQL commands too in it your server will do whatever those commands tell it to, this could range from adding a malformed entry to deleting everything in the database*/ 

    /* ######################################## Required Configuration 'Settings' Start ######################################## */ 
    /* Please only change things between the "" characters unless you know what you're doing */ 
    /* Add your IMAP email server credentials in the next 3 lines */ 
    $mailbox = "{imap.gmail.com:993/imap/ssl}INBOX"; /* This bit tells the script where to look and what folder to look for (you may need to change INBOX to the apropriate folder name) */ 
    $emailAddress = "the_address_to_read_emails_from"; /* The email you wish to process emails from */ 
    $emailPassword = "the_password_for_the_above_address"; /* The password associated with the above username */ 
    /* Add your SQL database credentials in the below 4 lines*/ 
    $databaseHost = "localhost"; /* put the address/hostname of your database here */ 
    $dbUsername = "root"; /* put an admin username here, or at least one with write (s) */ 
    $dbPassword = ""; /* put the corresponding admin password here */ 
    $databaseName = "testdb"; /* The name of the database the script should look at */ 
    /* ######################################### Required Configuration 'Settings' End ######################################### */ 



    /* ######################################## Optional Configuration 'Settings' Start ######################################## */ 
    /* These are here just encase you change your table names */ 
    $cT = "crew_tab"; /* The name of the first table the script should look at */ 
    $eT = "entry_tab"; /* The name of the second table the script should look at */ 
    /* ######################################### Optional Configuration 'Settings' End ######################################### */ 

    $fieldSeparator = ","; 
    $lineSeparator = "\n"; 
    $csvFile = 'csv.csv'; 


    if(!file_exists($csvFile)) { 
    die("No CSV, Skipping to next email"); 
    } 
    try { 
     /* try to make a connection to the SQL server*/ 
     $twoDArray = array(); 
     if (($handle = fopen("csv.csv", "r")) !== FALSE) { 
      while (($data = fgetcsv($handle, 0, $fieldSeparator)) !== FALSE) { 
       $twoDArray[] = $data; 
      } 
      fclose($handle); 
     } 
     echo $twoDArray[0][1]; 
     $database = new PDO("mysql:host=$databaseHost;dbname=$databaseName", $dbUsername, $dbPassword, 
      array(
       PDO::MYSQL_ATTR_LOCAL_INFILE => true, 
       PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
      ) 

     ); 
    } catch (PDOException $e) { 
     die("Database connection failed: ".$e->getMessage()); 
    } 
    foreach($twoDArray as $oneDArray){ 
     foreach($oneDArray as $row){ 
     $affectedRows = $database->exec(" 
     LOAD DATA LOCAL INFILE ".$database->quote($row)." INTO TABLE `$eT` 
      FIELDS TERMINATED BY ".$database->quote($fieldSeparator)." 
      LINES TERMINATED BY ".$database->quote($lineSeparator)); 
     } 
    } 
    echo "\nLoaded a total of $affectedRows records from the csv file into the database.\n"; 


    /* try to make a connection to the email server*/ 
    $inbox = imap_open($mailbox,$emailAddress,$emailPassword) or die('Failed to connect to Gmail: ' . imap_last_error()); 
    set_time_limit(3000); 
    $emailAddresss = imap_search($database, 'FROM "[email protected]"'); 
    /* if any emails are found, the script will iterate through each of them */ 
    if($emailAddresss) { 
     $count = 1; 
     /* sorts by newest first */ 
     rsort($emailAddresss); 
     /* for every value in emailAddress... */ 
     foreach($emailAddresss as $emailAddressNumber){ 
      /* get information specific to this email */ 
      $overview = imap_fetch_overview($inbox,$emailAddressNumber,0); 
      $message = imap_fetchbody($inbox,$emailAddressNumber,2); 
      /* get mail structure */ 
      $structure = imap_fetchstructure($inbox, $emailAddressNumber); 
      $attachments = array(); 
      /* if any attachments found... */ 
      if(isset($structure->parts) && count($structure->parts)){ 
       for($i = 0; $i < count($structure->parts); $i++){ 
        $attachments[$i] = array(
         'is_attachment' => false, 
         'filename' => '', 
         'name' => '', 
         'attachment' => '', 
        ); 
        if($structure->parts[$i]->ifdparameters){ 
         foreach($structure->parts[$i]->dparameters as $object){ 
          if(strtolower($object->attribute) == 'filename') 
          { 
           $attachments[$i]['is_attachment'] = true; 
           $attachments[$i]['filename'] = $object->value; 
          } 
         } 
        } 
        if($structure->parts[$i]->ifparameters){ 
         foreach($structure->parts[$i]->parameters as $object){ 
          if(strtolower($object->attribute) == 'name'){ 
           $attachments[$i]['is_attachment'] = true; 
           $attachments[$i]['name'] = $object->value; 
          } 
         } 
        } 
        if($attachments[$i]['is_attachment']){ 
         $attachments[$i]['attachment'] = imap_fetchbody($inbox, $emailAddressNumber, $i+1); 
         /* Extracts the email contents into usable text, 3 = BASE64 encoding*/ 
         if($structure->parts[$i]->encoding == 3){ 
          $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']); 
         } 
         /* 4 = QUOTED-PRINTABLE encoding */ 
         elseif($structure->parts[$i]->encoding == 4){ 
          $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']); 
         } 
        } 
       } 
      } 
      /* iterate through each attachment and save it */ 
      foreach($attachments as $attachment){ 
       if(($attachment['is_attachment'] == 1)) 
       { 
        $filename = $attachment['name']; 
        if(empty($filename)) $filename = $attachment['filename']; 

        if(empty($filename)) $filename = time() . ".dat"; 
        $folder = "attachment"; 
        if(!is_dir($folder)){ 
         mkdir($folder); 
        } 
        $fp = fopen("./". $folder ."/". $emailAddressNumber . "-" . $filename, "w+"); 
        fwrite($fp, $attachment['attachment']); 
        fclose($fp); 
       } 
      } 
     } 
    } 
    /* close the connection to the email_address server */ 
    imap_close($inbox); 

    echo "####################Script ran with no errors####################"; 
?> 

오류 :

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INTO TABLE entry_tab FIELDS TERMINATED BY ',' LINES TERM' at line 1 in C:\xampp\htdocs\main.php:59 Stack trace: #0 C:\xampp\htdocs\main.php(59): PDO->exec('\r\n LOAD ...') #1 {main} thrown in C:\xampp\htdocs\main.php on line 59

누군가가이 문제를 해결하는 데 도움 수 있습니다하십시오

문제는 다음 코드의 라인 57에 발생합니다.

미리 도움을 청하십시오.

답변

1

당신이 시도 할 수있는 쿼리를 인쇄하고 그것으로 무슨 잘못보고 그것을 실행하기 전에 die($query);을 시도하십시오 쿼리를 확인하는 것 외에

$query = "LOAD DATA LOCAL INFILE ".$database->quote($row)." INTO TABLE `$eT` 
       FIELDS TERMINATED BY ".$database->quote($fieldSeparator)." 
       LINES TERMINATED BY ".$database->quote($lineSeparator)); 


$affectedRows = $database->exec($query); 

다음

관련 문제