我有一个CSV文件,地址栏中有逗号:
"Name", "Address"
"Jim","1234, Clinton St, 12345"
我用来逃避逗号的代码是:
//In a loop
$col[$x]=mysqli_real_escape_string($con, $slice[$x]);
当我插入此内容时:
$query="INSERT INTO table(Name,Address) VALUES('$col[0]','$col[1]')";
$stmte=$dbh->prepare($query);
$stmte->execute();
它尝试在数据库中为Address字段创建三列。
除了使用正则表达式之外,还有其他解决方法吗?我急于解决这个问题,没有时间去探索正则表达式的概念。
代码:
if (($handle = fopen('./data/' . $filename, "r")) !== FALSE)
{
$fp = file('./data/' . $filename, FILE_SKIP_EMPTY_LINES);
$rowCount = count($fp);
$data = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$cnt++;
$num = count($data);
// echo $num;
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
// Insert into businesses
// $con = new PDO('mysql:host=localhost;dbname=table', 'username', 'password');
$col=array();
$hostname="lh";
$username="username";
$password="password";
$dbh = new PDO("mysql:host=$hostname;dbname=db", $username, $password);
for ($x=0;$x<19;$x++)
$col[$x]=mysqli_real_escape_string($con, $slice[$x]);
$query = "INSERT INTO table(Name, Address, City, State, Zipcode, Mailingaddress, Website, Email, Phone, Category, Membertype, Yearjoined, Contactname, Contactemail, Notes, Memberdiscounts, Photo, Longitude, Latitude)
VALUES('$col[0]','$col[1]','$col[2]','$col[3]','$col[4]','$col[5]','$col[6]','$col[7]','$col [8]','$col[9]','$col[10]','$col[11]','$col[12]','$col[13]','$col[14]','$col[15]','$col[16]', '$col[17]','$col[18]')";
$stmte=$dbh->prepare($query);
$stmte->execute();
我已经弄清楚问题是什么,但不是它的解决方案。据我所知,问题是当行被内爆时,输出是逗号分隔值。
找到解决方案。刚刚删除了implode / explode代码并直接处理了$ result数据。效果很好。
答案 0 :(得分:0)
而不是爆炸然后爆炸,只需:
$slice = $data;
因为$data
已经是csv列的数组。