<?php
global $wpdb;
// Table name
$tablename = $wpdb->prefix."customplugin";
// Import CSV
if(isset($_POST['butimport'])){
// File extension
$extension = pathinfo($_FILES['import_file']['name'], PATHINFO_EXTENSION);
// If file extension is 'csv'
if(!empty($_FILES['import_file']['name']) && $extension == 'csv'){
$totalInserted = 0;
// Open file in read mode
$csvFile = fopen($_FILES['import_file']['tmp_name'], 'r');
fgetcsv($csvFile); // Skipping header row
// Read file
while(($csvData = fgetcsv($csvFile)) !== FALSE){
$csvData = array_map("utf8_encode", $csvData);
// Row column length
$dataLen = count($csvData);
// Skip row if length != 4
if( !($dataLen == 4) ) continue;
// Assign value to variables
$name = trim($csvData[0]);
$username = trim($csvData[1]);
$email = trim($csvData[2]);
$age = trim($csvData[3]);
// Check record already exists or not
$cntSQL = "SELECT count(*) as count FROM {$tablename} where username='".$username."'";
$record = $wpdb->get_results($cntSQL, OBJECT);
if($record[0]->count==0){
// Check if variable is empty or not
if(!empty($name) && !empty($username) && !empty($email) && !empty($age) ) {
// Insert Record
$wpdb->insert($tablename, array(
'name' =>$name,
'username' =>$username,
'email' =>$email,
'age' => $age
));
if($wpdb->insert_id > 0){
$totalInserted++;
}
}
}
}
echo "<h3 style='color: green;'>Total record Inserted : ".$totalInserted."</h3>";
}else{
echo "<h3 style='color: red;'>Invalid Extension</h3>";
}
}
?>
<h2>All Entries</h2>
<!-- Form -->
<form method='post' action='<?= $_SERVER['REQUEST_URI']; ?>' enctype='multipart/form-data'>
<input type="file" name="import_file" >
<input type="submit" name="butimport" value="Import">
</form>
<!-- Record List -->
<table width='100%' border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>S.no</th>
<th>Name</th>
<th>Username</th>
<th>Email</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
// Fetch records
$entriesList = $wpdb->get_results("SELECT * FROM ".$tablename." order by id desc");
if(count($entriesList) > 0){
$count = 0;
foreach($entriesList as $entry){
$id = $entry->id;
$name = $entry->name;
$username = $entry->username;
$email = $entry->email;
$age = $entry->age;
echo "<tr>
<td>".++$count."</td>
<td>".$name."</td>
<td>".$username."</td>
<td>".$email."</td>
<td>".$age."</td>
</tr>
";
}
}else{
echo "<tr><td colspan='5'>No record found</td></tr>";
}
?>
</tbody>
</table>
LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
$csvData = array_map("utf8_encode", $csvData);
$csvData = array_map(function($value) {
return iconv("Windows-1251", "UTF-8", $value);
}, $csvData);