问题:
将从文本文件生成的每个数组转换为SQL查询。我有一个包含此类机场信息的文本文件:https://abc-supervisor.c9users.io/airports.txt
如果您不想点击链接,请参阅以下示例:
1,"Goroka","Goroka","Papua New Guinea","GKA","AYGA",-6.081689,145.391881,5282,10,"U","Pacific/Port_Moresby"
2,"Madang","Madang","Papua New Guinea","MAG","AYMD",-5.207083,145.7887,20,10,"U","Pacific/Port_Moresby"
3,"Mount Hagen","Mount Hagen","Papua New Guinea","HGU","AYMH",-5.826789,144.295861,5388,10,"U","Pacific/Port_Moresby"
我正在尝试将每个值都放入SQL表中。
PHP:
<?php
$lines = file('airports.txt');
echo '<xmp>';
$airport = array();
foreach($lines as $row)
{
$airport = str_replace('"', '', explode(",", $row));
print_r($airport);
}
echo '</xmp>';
?>
输出:
Array
(
[0] => 1
[1] => Goroka
[2] => Goroka
[3] => Papua New Guinea
[4] => GKA
[5] => AYGA
[6] => -6.081689
[7] => 145.391881
[8] => 5282
[9] => 10
[10] => U
[11] => Pacific/Port_Moresby
)
Array
(
[0] => 2
[1] => Madang
[2] => Madang
[3] => Papua New Guinea
[4] => MAG
[5] => AYMD
[6] => -5.207083
[7] => 145.7887
[8] => 20
[9] => 10
[10] => U
[11] => Pacific/Port_Moresby
)
期望的输出:
将每个值插入SQL中的一行。感谢有人能指出正确的方向。
答案 0 :(得分:1)
我认为你想要读取CSV文件并将每一行加载到数据库表的一行。
如果MySQL服务器可以访问该文件,则最简单的方法是使用LOAD DATA INFILE。像这样的东西(没有经过测试,也没有经常使用的东西)
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("LOAD DATA INFILE 'airports.txt'
INTO TABLE expenses
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
(col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11)");
但是假设您可能希望事先对某些值进行其他处理,或者无法从MySQL访问该文件,那么您可能只想手动插入每一行(请注意,您可以插入多行这会更有效率,但这是一个单独的问题。)
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (($handle = fopen('airports.txt', "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if ($stmt = $mysqli->prepare("INSERT INTO some_table(col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")) {
$stmt->bind_param("isssssddiiss", $data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6], $data[7], $data[8], $data[9], $data[10], $data[11]);
$stmt->execute();
}
}
fclose($handle);
}
答案 1 :(得分:0)
json将其存储在数据库中
foreach($lines as $row)
{
$airport = str_replace('"', '', explode(",", $row));
$json = json_encode($airport );
//Code to store $json in database
}
检索数据时,可以使用json_decode对其进行解码。
if you want to store field wise you can do this
foreach ($airport as $key => $field) {
for($i=0;$i<11;$i++){
if($key == 'i') {
$value[$i] = $field; }
$sql = "INSERT INTO table name (fields1,fields2,...) values ($value[0],$value[1]...); }
答案 2 :(得分:-2)
foreach ($airport as $key => $value)
{
$sql = "INSERT INTO table name (fields1,fields2,...) values ($value[0],$value[1]...)
}