WordPress插件无法将CSV数据导入自定义数据库表问题排查
问题分析与修复方案
核心错误点
- 列数判断逻辑错误:你的CSV每行包含5个字段,但代码中判断
if( !($dataLen == 4) ) continue;,导致所有行被直接跳过,根本不会执行插入操作。 - SQL语句存在风险与逻辑问题:直接拼接SQL查询字符串,既存在SQL注入风险,若
price字段为数值类型,单引号包裹会导致查询结果错误,无法正确判断记录是否存在。 - 插入成功判断失效:
$wpdb->insert_id仅适用于带自增主键的表,若你的表主键不是自增,该值始终为0,无法统计真实插入数量,应改用$wpdb->rows_affected。 - 不必要的编码转换:
utf8_encode可能导致原本UTF-8编码的CSV数据乱码,进而触发后续非空判断失败。
修复后的完整代码
<?php global $wpdb; // Table name $tablename = $wpdb->prefix . "bohio"; // 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']) && strtolower($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) { // 移除不必要的utf8_encode,若CSV确为ISO-8859-1编码可重新启用 // $csvData = array_map("utf8_encode", $csvData); // Row column length $dataLen = count($csvData); // Skip row if length != 5(CSV每行对应5个字段) if ($dataLen != 5) continue; // Assign value to variables $square_feet = trim($csvData[0]); $bed = trim($csvData[1]); $bath = trim($csvData[2]); $bh_service = trim($csvData[3]); $price = trim($csvData[4]); // Check record already exists or not - 使用prepare避免注入风险 $cntSQL = $wpdb->prepare( "SELECT count(*) as count FROM {$tablename} where price = %s", $price ); $record = $wpdb->get_results($cntSQL, OBJECT); if ($record[0]->count == 0) { // Check if variable is empty or not if (!empty($square_feet) && !empty($bed) && !empty($bath) && !empty($bh_service) && !empty($price)) { // Insert Record $wpdb->insert($tablename, array( 'square_feet' => $square_feet, 'bed' => $bed, 'bath' => $bath, 'bh_service' => $bh_service, 'price' => $price )); // 使用rows_affected判断插入是否成功 if ($wpdb->rows_affected > 0) { $totalInserted++; } } } } echo "<h3 class='bohio_valid'>Total record Inserted : " . $totalInserted . "</h3>"; } else { echo "<h3 class='bohio_invalid'>Invalid File Extension</h3>"; } } ?>
额外检查项
- 确认自定义表
{$wpdb->prefix}bohio已创建,且字段square_feet、bed、bath、bh_service、price的类型与CSV数据匹配(例如price若为DECIMAL类型,需确保CSV数值格式正确)。 - 确保上传表单添加了
enctype="multipart/form-data"属性,否则无法接收上传文件:<form method="post" enctype="multipart/form-data"> <input type="file" name="import_file"> <input type="submit" name="butimport" value="Import"> </form> - 检查WordPress权限,确保当前用户拥有数据库写入权限,且服务器上传目录可读写。
内容的提问来源于stack exchange,提问作者Naik Javaid
相关产品推荐
相关产品推荐

