我试图将从json获取的数据输入到数据库中。我已经将数据作为多维数组获取并使用foreach循环遍历数组。
我试图将此数据插入到mysql数据库中,但我一直收到错误错误:字段'摘要'没有默认值。
我的数据库表在名为tracking的数据库中称为文章,并包含以下字段: article_id,url,domain,favicon,title,summary,likes,tweets,plusones,image,category
我的php文件名为 json_parser.php ,如下所示
<?php
define('DB_NAME', 'tracking');
define('DB_USER', 'xxxxxxxxxxx');
define('DB_PASSWORD', 'xxxxxxxxx');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cannot use '. DB_NAME . ': ' .mysql_error());
}
$url = "http://digitalrand.net/api/url_data/?key=abacus&pass=aba123cuxza%";
$json = file_get_contents($url);
$obj = json_decode($json, true);
foreach($obj as $article_array){
$url = $article_array['url'];
$domain = $article_array['domain'];
$favicon = $article_array['favicon'];
$title = $article_array['title'];
$category = $article_array['category'];
echo $category . "<br>";
echo $domain . "<br>";
echo $favicon . "<br>";
echo $title . "<br>";
echo $url . "<br>";
$sql = 'INSERT INTO articles '.
'(url, domain, favicon, title) '.
'VALUES ( "$url", "$domain","$favicon","$title" )';
if (mysql_query($sql)){
echo "success.......";
}
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
$large_summary = $article_array['summary'];
foreach ($large_summary as $summary){
mysql_query("INSERT INTO articles(summary) VALUES('$summary')");
echo "$summary <br>";
}
$images = $article_array['images'];
foreach ($images as $image){
$image_first= reset($image);
echo $image_first;
mysql_query("INSERT INTO articles(image) VALUES($image_first)");
echo "<img src=$image_first>";
}
$social_shares = $article_array['social_shares'];
foreach($social_shares as $social_share=>$include){
echo $social_share . ": " . $include . "<br>";
}
$entities = $article_array["entities"];
foreach($entities as $entity_cat=>$entities_arr){
foreach($entities_arr as $key=>$entity){
echo $entity_cat.' >> '.$entity. "<br>";
}
}
}
?>
如何遍历数组项并将其显示在适当的字段
答案 0 :(得分:0)
首先,您的代码中存在错误:
foreach ($large_summary as $summary){
mysql_query("INSERT INTO articles(summary) VALUES($summary)");
echo "$summary
";
}
foreach ($large_summary as $summary){
mysql_query("INSERT INTO articles(summary) VALUES('$summary')");
echo "$summary
";
}
然后,请记住,您只使用(url, domain, favicon, title)
字段插入行,然后只有(summary)
的某些行,然后只有(image)
的其他行。
我想你不想插入同一行吗?
然后,如果你不能使其有效,你必须设置一个默认值:
ALTER TABLE `articles` CHANGE `summary` `summary` TEXT NULL DEFAULT NULL;
[编辑回答Mutuma评论]
您的数据库未正确设置。对于一组(url, domain, favicon, title)
,你几乎没有sumaries。
所以你必须创建另一个表,例如summaries
和(id, ref_article, summary)
...
对于images
来说它也是一样的!
请重新考虑基础结构。