PHP导入TXT数据至SQL Server遇未定义数组键错误求助
解决PHP导入TXT到SQL Server时的“Undefined array key 1”警告
问题描述
使用PHP将TXT文件数据导入SQL Server数据库,功能可正常运行,但持续出现“Undefined array key 1”的警告错误,需排查解决。
TXT数据内容
ankit,ankit@gmail.com swapnil, swapnil@gmail.com shefali, shefali@gmail.com abhishek, abhishek@gmail.com
PHP实现代码
<?php include 'connection.php'; $open = fopen('employee.txt','r'); while (!feof($open)) { $getTextLine = fgets($open); $explodeLine = explode(",",$getTextLine); list($name,$email) = $explodeLine; $qry = "insert into employees (name,email) values('".$name."','".$email."')"; $run = sqlsrv_query($conn,$qry); } fclose($open); ?>
SQL表创建语句
CREATE TABLE employees(name VARCHAR(255) ,email VARCHAR(255) );
错误信息
Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18
问题原因及解决方案
原因
TXT文件中存在空行,fgets()读取空行后,explode(",", $getTextLine)得到的数组元素不足2个,而list($name,$email)强制要求数组有2个元素,因此触发警告。此外原代码存在SQL注入风险,且缺乏错误处理。
解决步骤
- 读取每行后先去除首尾空白(含换行符),若处理后为空则跳过该行;
- 使用参数化查询避免SQL注入;
- 添加基础错误处理,排查数据库操作问题。
修改后的代码
<?php include 'connection.php'; $open = fopen('employee.txt', 'r'); if (!$open) { die("无法打开文件"); } while (!feof($open)) { $getTextLine = fgets($open); // 去除首尾空白(包括换行、空格) $trimmedLine = trim($getTextLine); // 跳过空行 if (empty($trimmedLine)) { continue; } $explodeLine = explode(",", $trimmedLine); // 确保分割后有2个有效元素 if (count($explodeLine) !== 2) { continue; } $name = trim($explodeLine[0]); $email = trim($explodeLine[1]); // 参数化查询避免SQL注入 $qry = "INSERT INTO employees (name, email) VALUES (?, ?)"; $params = array($name, $email); $run = sqlsrv_query($conn, $qry, $params); // 输出数据库操作错误信息 if (!$run) { $errors = sqlsrv_errors(); print_r($errors); } } fclose($open); ?>
内容的提问来源于stack exchange,提问作者Piya Tiwari
相关产品推荐
相关产品推荐

