【发布时间】:2014-03-21 11:20:59
【问题描述】:
我正在尝试将从 json 获取的数据输入到数据库中。我已将数据作为多维数组获取,并使用 foreach 循环遍历数组。
我正在尝试将此数据插入 mysql 数据库,但我不断收到错误错误:字段“摘要”没有默认值。
我的数据库表在名为 tracking 的数据库中称为文章,并具有以下字段:article_id、url、域、favicon、标题、摘要、喜欢、推文、plusones、图像、类别
我的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>";
}
}
}
?>
如何循环遍历数组项并将它们显示在适当的字段中
【问题讨论】:
-
summary 的数据类型是什么,看起来它设置为 NOT NULL,所以将其设为 NULL。
-
我已经尝试删除该列并重新插入它,但它默认设置为 null,即 ALTER TABLE
articlesADDsummaryTEXT NOT NULL ;跨度> -
您真的不想插入没有摘要但有
url, domain, favicon, title的行和另一个有summary或image但没有其他字段的行吗?因为这是你在做的! -
对于字符串数据,在将它们添加到数据库之前,您需要将它们括在引号中。
-
@AbhikChakraborty ...我已经更正了。