我正在学习php / sql / wamp并且在学习项目上遇到了很多麻烦...
我有一个下面的txt文件我终于想通了把它加载到php然而我无法弄清楚如何创建数据库sql需要插入这些数据并执行查询...是否有一个很好的链接或教程或者样本代码?下面是我的php和txt代码
<?php
error_reporting(E_ERROR);
$header = '<?xml version="1.0" encoding="UTF-8"?>'."\n<datalist>";
$content = $header."\n".file_get_contents("data.txt")."\n</datalist>";
$ob = simplexml_load_string($content);
$json = json_encode($ob);
$array = json_decode($json, true);
$alldata = $array["pub"];
foreach ($alldata as $key => $value) { //access all data in loop
$id = $value["ID"];
$title = $value["title"];
$year = $value["year"];
$booktitle = $value["booktitle"];
$pages = $value["pages"];
$authors = implode(",", $value["authors"]["author"]);
//All process data can available here .run your sql query for insert.
}
?>
和我的txt文件下面..相同的格式,但50mb的数据
<pub>
<ID>0</ID>
<title>Regression Time Warping for Similarity Measure of Sequence</title>
<year>2004</year>
<booktitle>CIT</booktitle>
<pages>826-830</pages>
<authors>
<author>Hansheng Lei</author>
<author>Venu Govindaraju</author>
</authors>
</pub>
<pub>
<ID>1</ID>
<title>A Computational Model for Face Location Based on Cognitive Principles</title>
<year>1992</year>
<booktitle>AAAI</booktitle>
<pages>350-355</pages>
<authors>
<author>Venu Govindaraju</author>
<author>Sargur N. Srihari</author>
<author>David B. Sher</author>
</authors>
</pub>
答案 0 :(得分:2)
在MySQL中创建表。然后使用mysqli(或PDO)插入数据。
/**
* Connect to database
*/
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/**
* Loop data
*/
foreach ($alldata as $key => $value) { //access all data in loop
/**
* Insert row. This assumes that your table columns are in the
* same order as the variables as they are given below
*/
$authors = implode(",", $value["authors"]["author"]);
$stmt = $mysqli->prepare("INSERT INTO your_table VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss',
$value["ID"],
$value["title"],
$value["year"],
$value["booktitle"],
$value["pages"], implode(",", $value["authors"]["author"]));
$stmt->execute();
}
来自http://us1.php.net/manual/en/mysqli-stmt.bind-param.php。
请注意,可以使用MySQL插入多个记录。 (Inserting multiple rows in mysql。)您可以这样做以减少插入数量,但这会使查询构建更加复杂。
另请注意,对此数据使用单个表格并不是最佳选择。理想情况下,您将使用三个表:
考虑使用单个表时出现以下问题:
答案 1 :(得分:-1)
在for循环之前,您需要连接到数据库,然后在for循环中,您需要插入从数据文件中读取的每一行。你的表结构是什么样的?您是否尝试自己编写任何SQL?
连接数据库:http://jadendreamer.wordpress.com/2011/01/25/connecting-to-a-mysql-database-using-php/