AJAX PHP MySQL CSV

Uploading a CSV file via a web form to populate a MySQL table with Ajax and PHP.

<div>
    <form class="form-inline" name="csv_form" id="csv_form" action="#" onsubmit="uploadCSV(this.id, 'DEST_PAGE.php?');" method="post" enctype="multipart/form-data">
        <fieldset>
            <label class="btn btn-default btn-file">
                <input name="csv_file" id="csv_file" type="file" />
                <input type="hidden" id="campname" name="campname" value="{{campname}}" />
                <div class="radio">
                    <label>
                        <input type="radio" id="newline" name="newline" value="\n">unix</label>
                </div>
                <div class="radio">
                    <label>
                        <input type="radio" id="newline" name="newline" value="\r\n">dos</label>
                </div>
                <div class="radio">
                    <input type="submit" class="btn btn-success btn-sm glyphicon glyphicon-upload" name="csv" id="csv" value="upload" />
                </div>
            </label>
        </fieldset>
    </form>
</div>

javascript

    function uploadCSV(id, dst) {
        var getdata = $('#' + id).serialize();
        var file_data = $('#csv_file').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajax({
            url: dst + getdata,
            dataType: 'text',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function(data) {
                alert(data);
            }
        });
    }

php

if (isset($_GET['newline'])) {
	$nl = $_GET['newline'];
} else {
	$nl = '\r\n';
}
if (0 < $_FILES['file']['error']) {
	echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
	$campname = $_GET['campname'];
	$path = getcwd();
	move_uploaded_file($_FILES['file']['tmp_name'], 'csv/' . $campname . '.csv');
	$sql = $mysqli->query("LOAD DATA INFILE '$path/csv/$campname.csv'
                 IGNORE INTO TABLE numbers
                 CHARACTER SET UTF8
                 FIELDS TERMINATED BY ','
                 OPTIONALLY ENCLOSED BY '\"'
                 LINES TERMINATED BY '$nl'
                 (`number`, `last_name`, `name`, `middle_name`, `born`) set `camp` = '$campname', `status` = 'NOANS'");
}
Только авторизованные участники могут оставлять комментарии.
  • blog/ajax_php_load_csv.txt
  • Последние изменения: 2018/07/04