【发布时间】:2018-03-31 07:08:18
【问题描述】:
我有以下示例 json 文件,我正在尝试用它填充 MySQL 表。使用 json 数据填充 books 表不起作用且没有错误。我想知道以下 PHP 代码有什么问题:
<?php
$connect=new PDO('mysql:host=localhost;dbname=books','root','0000');
$filename= "data.json";
$data=file_get_contents($filename);
$array=json_decode($data,true);
$stmt=$connect->prepare("INSERT INTO books values(?,?,?,?,?,?,?,?,?)");
foreach($array["books"] as $row){
$stmt->bindParam(1,$row['isbn']);
$stmt->bindParam(2,$row['title']);
$stmt->bindParam(3,$row['subtitle']);
$stmt->bindParam(4,$row['author']);
$stmt->bindParam(5,$row['published']);
$stmt->bindParam(6,$row['publisher']);
$stmt->bindParam(7,$row['pages']);
$stmt->bindParam(8,$row['description']);
$stmt->bindParam(9,$row['website']);
$stmt->execute();
}
?>
json 文件如下所示:
{
"books":[
{
"isbn":"9781593275846",
"title":"Eloquent JavaScript, Second Edition",
"subtitle":"A Modern Introduction to Programming",
"author":"Marijn Haverbeke",
"published":"2014-12-14T00:00:00.000Z",
"publisher":"No Starch Press",
"pages":472,
"description":"JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications.",
"website":"http://eloquentjavascript.net/"
},
{
"isbn":"9781449331818",
"title":"Learning JavaScript Design Patterns",
"subtitle":"A JavaScript and jQuery Developer's Guide",
"author":"Addy Osmani",
"published":"2012-07-01T00:00:00.000Z",
"publisher":"O'Reilly Media",
"pages":254,
"description":"With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you.",
"website":"http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/"
} ] }
Mysql的表结构是这样的:
--- Table structure for table `books`
--
CREATE TABLE `books` (
`isbn` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`subtitle` varchar(50) NOT NULL,
`author` varchar(50) NOT NULL,
`published` date NOT NULL,
`publisher` varchar(50) NOT NULL,
`pages` int(11) NOT NULL,
`description` text NOT NULL,
`website` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
【问题讨论】:
-
$stmt=$connect->prepare("INSERT INTO books (add coloum here) values(?,?,?,?,?,?,?,?,?)");
-
我添加了这样的列名: $stmt=$connect->prepare("INSERT INTO books (isbn,title,subtitle,author,published,publisher,pages,description,website) values( ?,?,?,?,?,?,?,?,?)");仍然没有插入数据
-
你能说明错误是什么吗?
-
没有错误但是我去phpmyadmin查看是否插入了数据,发现没有插入任何数据!
-
$stmt->bind_param("sssssssss", $row['isbn'],$row['title'],$row['subtitle'],$row['author'], $row['published'],$row['publisher'],$row['pages'],$row['description'],$row['website']);
标签: php mysql json phpmyadmin