PHP导入的CSV数据遇到逗号时截短
我有一个简单的 PHP 脚本,它循环 CSV 文件中的数据,并将记录相应地添加到数据库中。我的字段之一是描述字段,但该描述字段本身有一个逗号(或多个逗号)。似乎该字段的数据仅读取到逗号为止,但是下一个字段是正确的,因此后面的字段并不是描述的其余部分,而是使用正确的下一列。
我应该逃避逗号吗?我正在将这些数据添加到 MySQL 数据库,这可能是导致问题的原因吗?
我的 SQL 查询可能类似于:
$description = $data[7]; //description column eg: "hello, my name is xxxxx, I am old"
INSERT INTO tblsomething (id, description) VALUES ($id, '$description');
上面的语句仅插入描述为“hello”,在遇到的第一个逗号后不插入任何内容。
有什么想法吗?
非常感谢, 西蒙
编辑:问题已经解决,向所有人道歉,因为这是一个愚蠢的错误。看来做前端的人正在使用模式“,”来分割内容来创建内容数组。似乎该描述(尽管应该是一个数组条目)由于包含逗号而被拆分为多个条目。这可以通过使用更罕见的字符(例如管道符号)来创建分隔符来解决。
感谢大家
I have a simple PHP script that loops over data in a CSV file, and adds the records to the database accordingly. One of my fields is a description field, but that description field itself has a comma (or multiple comma's) in it. It seems as though data for that field is only read up until the comma, however the next field is correct, so it is not as though the field after that is the remainder of the description, is is using the next column which is right.
Am I supposed to escape the comma? I am adding this data to a MySQL database, could that be where the issue is being caused?
My SQL query could be something like:
$description = $data[7]; //description column eg: "hello, my name is xxxxx, I am old"
INSERT INTO tblsomething (id, description) VALUES ($id, '$description');
The above statement only inserts the description as "hello" and nothing after the first comma it encounters.
Any ideas why this is?
Many thanks,
Simon
EDIT: This is solved, apologies to all as it was a silly mistake. It appears that the person who did the front end was creating arrays of content using the patter ',' to split the content. IT seems that the description - although supposed to be one array entry - was being split into multiple entries due to it containing comma's. This will be solved by using a more rare character like the pipe symbol to create our separators.
Thanks to all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为它不是 CSV 文件。 CSV 文件中包含逗号的字段应该用双引号分隔;这样 PHP 中的 CSV 函数将正确处理它们。
Because it's not a CSV file. Fields in a CSV file that contain commas are supposed to be delimited by double quotes; this way the CSV functions in PHP will handle them properly.