0

Ok so the issue i am having now is that I just straight up don't understand how to pass data to the LOAD DATA LOCAL INFILE SQL command using the exec() function.

On line 57 in my code i have tried using implode(',',$row). I have also tried using serialize($row) and first i tried quote like the next 2 lines i have also tried giving it every param and value manually which semi works but is impractical as there will be well over 100 entries on every line in the imported CSV file, there must be a better way to do this and id love if someone could show me how.

The issue occurs on line 57 of the following code:

<?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####################";
?>

The error that is occurring is:

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

Please can someone help me to resolve this issue.

Thanks in advance for any help.

1 Answer 1

1

can you try the following

    $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);

but to check the query please try die($query); before you execute it to print the query and see whats wrong with it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.