So my site parses JSON data, and breaks it into separate stories from the NY Times API.
I'm trying to load those separate stories into my MySQL database.
The code below runs the page but getting an error:
A Database Error Occurred
You must use the "set" method to update an entry.
Filename: /Applications/MAMP/htdocs/topline/controllers/index.php
Line Number: 29
Took out my api key below.
Model
<?php
class Api_model extends CI_Model {
public function __construct() {
} // End of construct
public $offset;
public function get_news() {
$offset = 0;
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://api.nytimes.com/svc/mostpopular/v2/mostviewed/all-sections/1.json?offset=" . $offset . "&api-key=mykey");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$Obj = json_decode($output);
return $Obj;
} // End of function
} // End of class
?>
View
<section>
<?php
$paginate = site_url('/pageup');
//loop through json response items
foreach ($articles->results as $article){
//error reporting turned off for this process because some objects have more than 1 photo
error_reporting(0);
echo "<div class='story'>";
echo "<div class='photo'>";
//pass image into an img tag
echo "<img src='" . $article->media[0]->{"media-metadata"}[0]->url . "' />";
echo "</div>";
echo "<div class='story-text'>";
//call the story headline
echo "<h3>" . $article->title . "</h3>";
//call the description
echo "<p>" . $article->abstract . "</p>";
//call the link to the full story
echo "<p class='btn btn-primary'><a href='" . $article->url . "' target='_blank'>Read More</a></p>";
echo "</div>";
echo "</div>";
//setup database array
$article_data = array(
'id' => 1,
'image' => $article->media[0]->{"media-metadata"}[0]->url,
'body' => $article->abstract,
'title' => $article->title,
'link' => $article->url
);
}
//var_dump($articles->results[0]);
?>
<p><a href="<?php echo $paginate; ?>" class="btn btn-block">Load More Stories</a></p>
</section>
Controller
<?php
class Index extends CI_Controller
{
public function __construct() {
parent::__construct();
session_start();
}
public function index() {
$data['title'] = "Topline Press";
// Load the model
$this->load->model('Api_model');
// Call the method of the model
$data['articles'] = $this->Api_model->get_news();
// Load the views
$this->load->view('header', $data);
$this->load->view('start', $data);
$this->load->view('footer', $data);
//push story data into database
$this->db->insert('stories', $article_data);
}
} // End of class
?>
Fairly new at this so I appreciate any help. Thanks in advance.