我正在尝试编写一个php脚本,该脚本将文本文件分解其内容并将其插入到MySql数据库中,代码如下:
$file = "my_file.txt";
$db = "db_name";
$link = mysql_connect("localhost","root");
if(!$link) die("Connection Failed");
mysql_select_db($db) or die("Could not open $db: ".mysql_error()."<br />");
$fp = fopen($file, 'r') or die("Could not open file");
$my_filesize = filesize($file);
while(!feof($fp)) {
$prod_doc.=fread($fp, $my_filesize); // store the file in a variable
}
$prod_array = explode("~",$prod_doc); // create a array with the explode function
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
}
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('$prod_items[$i][0]','$prod_items[$i][1]','$prod_items[$i][2]')
";
$result = mysql_query($query);
if(!$result) die(mysql_error());
$result = mysql_affected_rows($result);
echo $result;
mysql_close($link); `
我的问题是这样的:Array[0]、Array[1]、Array[3] 是输入数据库的内容,而不是我的数据。预先感谢,干杯。
最佳答案
要访问双引号字符串内使用的数组变量元素值,需要大括号分隔符:
"'{$prod_items[$i][0]}','{$prod_items[$i][1]}','{$prod_items[$i][2]}') ";
另一种编码方法是通过串联(在这种情况下,您不需要额外的分隔符):
"'" . $prod_items[$i][0] . "','" . $prod_items[$i][1] . "','" . $prod_items[$i][2] . "') ";
不要忘记,如果输入数据不可预测,您需要过滤掉可能破坏续集或损害安全原则的字符。请参阅 How can I prevent SQL injection in PHP?
此外,junmats 的评论是正确的,您只是在 for 循环之外运行查询,这是没有意义的。
关于Php多维数组/MySql问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1824839/