I have this method below which is responsible for bringing me an array of objects (blog).
public function getListaBlogsById($id) {
$result = array();
try {
$statement = $this->getDb()->prepare('SELECT * FROM Blog WHERE categoria_id = :id');
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll();
} catch (Exception $ex) {
$ex->getTrace();
}
return $result;
}
And I know that the array is not null. What I want to do is to iterate the objects inside the array in this way:
<?php foreach ($blog_category as $item): ?>
<h2>
<?php echo $item->getTitle(); ?>
</h2>
<p class="lead">
by <?php echo $item->getAuthor(); ?>
</p>
<p><i class="fa fa-clock-o"></i> Postado em
<?php $date = strtotime($item->getDate());
$br_format = date("d/m/Y g:i A", $date);
echo $br_format;
?></p>
<hr>
<a href="<?php echo Utils::createLink('detail-post', array('id' => $item->getId())); ?>">
<img class="img-responsive img-hover" src="../web/img/1850_james_ancestry.JPG" alt=""/>
</a>
<hr>
<p><?php echo $item->getPre(); ?></p>
<a class="btn btn-primary" href="<?php echo Utils::createLink('detail-post', array('id' => $item->getId())); ?>">Leia mais <i class="fa fa-angle-right"></i></a>
<hr>
<?php endforeach; ?>
But the page renders nothing.
Any light will be appreciated.
The object that is used will have been created from strClass() and therefore does not have any get methods associated with it.
So change your script like so in order to access the properties of these objects directly rather than expecting them to have an associated ->getxxx() method.
<a href="<?php echo Utils::createLink('detail-post', array('id' => $item->id)); ?>">
<?php echo $item->title; ?>
</a>
The actual names of the properties will depend on the column names ( and column name case) you have on the table you queried.
You may also need to change this line in your getListaBlogsById($id) funtion to ensure that the data is returned as an object and not an array
From
$result = $statement->fetchAll();
To
$result = $statement->fetchAll(PDO::FETCH_CLASS);
Thanks #RiggsFolly for your help. I solve my problem making some modification as fallows:
public function getListaBlogsById($id) {
try {
$result = array();
$blog = new Blog();
$statement = $this->getDb()->prepare('SELECT * FROM Blog WHERE categoria_id = :id');
$statement->bindParam(':id', $id);
if ($statement->execute()) {
while ($row = $statement->fetch()) {
BlogMapper::map($blog, $row);
$result[$blog->getId()] = $blog;
}
}
} catch (Exception $ex) {
$ex->getTrace();
}
return $result;
}
and
public static function map(Blog $blog, array $properties) {
if (array_key_exists('id', $properties)) {
$blog->setId($properties['id']);
}
if (array_key_exists('blog_author', $properties)) {
$blog->setAuthor($properties['blog_author']);
}
if (array_key_exists('blog_article_title', $properties)) {
$blog->setTitle($properties['blog_article_title']);
}
if (array_key_exists('blog_date_creation', $properties)) {
$blog->setDate($properties['blog_date_creation']);
}
if (array_key_exists('blog_article_pre', $properties)) {
$blog->setPre($properties['blog_article_pre']);
}
if (array_key_exists('blog_article', $properties)) {
$blog->setArticle($properties['blog_article']);
}
if (array_key_exists('categoria_id', $properties)) {
$blog->setCategoria_id($properties['categoria_id']);
}
}
Related
I want to get a row from db and show in my page. Following code doesn't work and my browser hangs. and i don't know how fix it. Please help me.
Class :
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
return $stmt_select_calculate->execute();
}
index.php :
<?php
include("../db/Database.php");
$databse = new Database();
$menu = $databse->get_calculate(0);
while ($row_select_calculate = $menu) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row_select_calculate['title']?>
</a>
</li>
<?php
}
?>
First of all, $stmt_select_calculate->execute(); returns bool value. You cannot iterate over bool value, it's obvious. So, you should return statement object itself:
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
$stmt_select_calculate->execute();
return $stmt_select_calculate;
}
In index.php you should fetch data:
$menu_stmt = $databse->get_calculate(0);
while ($row = $menu_stmt->fetch()) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row['title']?>
</a>
</li>
<?php
}
In database table there is no rows means getting error Undefined variable: results using codeigniter,in case there is no row or empty table is there means i want to display view page
controller
$data['breview'] = $this->Profile_model->review();
$this->load->view('supplierreview', $data);
Model
public function review() {
$this->db->select('*');
$this->db->from('reviews');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = reviews.supplier_id');
$this->db->join('customer_registration', 'reviews.customer_id=customer_registration.id');
$this->db->join('sub3_category', 'reviews.product_id=sub3_category.id');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
view page
<?php
foreach ($breview as $row) {
?>
<div class="reviewsection">
<img src="<?php echo 'data:image;base64,' .$row->product_image; ?>" class="img-circle img-user" alt="" width="50px;" height="50px;"/>
<span class="starfont"><botton class="btn btn-danger"> <?php echo $row->ratings; ?> <span class="fa fa-star starfont"></span></botton> </span>
<div class="content-left">
<p><b>Product Name:<?php echo $row->product_name; ?></b></p>
<p><?php echo $row->review_msg; ?></p>
<?php $buyer_review = strtotime($row->review_date);?>
<?php $date=date('d-F-Y',$buyer_review); ?>
<p>Buyer Name : <?php echo $row->first_name; ?> <?php echo $date ; ?></p>
</div>
</div>
<?php } ?>
$results is not defined.
Please add $results = [];
Here you go:
$results = [];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
In my model, in most cases, i do the following
public function my_function() {
//$qry = YOUR_QUERY
if ($qry->num_rows() > 0) //or ==1 or whatever, depends on your structure
return $qry->result_array(); // or row_array, depends on your structure
return FALSE;
}
Then in your controller you can check if the result is FALSE or EMPTY like:
$result_from_model = $this->my_model->my_function();
if($result_from_model && !empty($result_from_model)) {
//your code here
}
You can use the following code :
return (is_array($results)?$results:array());
Hope it works.
All the answers given so far are good. Here is yet another way to do it. It's essentially the same as the accepted answer only using a ternary instead of if.
$query = $this->db->get();
return $query->num_rows() > 0 ? $query->result() : array();
}
I have a database table with (NumSection (id) and NomSection)
In my page I want display all data from 'NomSection' like a link. And when I click on the link I want open my actual page with a $_POST['nomSection'] and display data of this section.
From my page index.php :
<div>
<?php
$array = returnAllSection();
foreach ($array as $section) {
// link to same page but with a $_POST['NomSection'], For the //moment I just display it.. I don't know how do with php
echo $section['NomSection'].'<br/>';
}
?>
</div>
<div>
<?php
// here I want have $array = returnAll('NomSection) or returnAll() //if empty (this function return ALL if empty or All of a section, can I just //put returnAll($_POST[nomSection]) ?
$array = returnAll();
foreach ($array as $section) {
echo 'Titre: ' .$section['TitreArticle'].'<br/>';
echo 'Date: ' .$section['DateArticle'].'<br/>';
echo 'Texte: ' .$section['TexteArticle'].'<br/>';
echo '<br/>';
}
?>
</div>
my functions: (works good)
function returnAll($arg = 'all') {
global $connexion;
if($arg == 'all'){
$query = "select
NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection or RefSection = null;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
else {
$query = "select NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection and NomSection = :arg;";
$prep = $connexion->prepare($query);
$prep->bindValue(':arg', $arg, PDO::PARAM_STR);
$prep->execute();
return $prep->fetchAll();
}
}
function returnAllSection() {
global $connexion;
$query = "select * from Sections;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
In order to post you'll need to use a form or javascript ajax post, as far as I know. Here I show a clunky form post approach that might work for what you are trying to accomplish.
<?php
function returnAllSection() {
return array(
array('NomSection' => 'foo'),
array('NomSection' => 'bar'),
array('NomSection' => 'baz'),
);
}
?>
<?php
$array = returnAllSection();
foreach ($array as $section) { ?>
<form action="" method="POST">
<button type="submit">NomSection</button>
<input type="hidden" name="NomSection" value="<?php echo htmlspecialchars($section['NomSection']); ?>">
</form>
<?php } ?>
<?php
if (isset($_POST['NomSection'])) {
error_log(print_r($_POST,1).' '.__FILE__.' '.__LINE__,0);
// do something with NomSection...
}
?>
I'm working with CodeIgniter.
I need to get some data from database with a foreach loop.
I have 4 items in the database, but the loop retrieve only two of them (the items with id 2 and 4).
This is the code in the for the foreach in the controller:
$this->load->model('home_model');
$data['query']=$this->home_model->get_films($limit);
if ($data['query']) {
$data['main_content'] = 'home';
$data['film'] = array();
foreach($data['query'] as $film_info) {
$data['film'] = array(
'id' => $film_info->id,
'poster_src' => $film_info->film_poster_src,
'title' => $film_info->film_name,
'year' => $film_info->film_year,
'genre_id' => $film_info->genre_id,
);
$this->db->select('*');
$this->db->from('genres');
$this->db->where('id', $film_info->genre_id);
$query1 = $this->db->get();
$genre_info = $query1->row();
$data['genre_name'] = $genre_info->genre_name;
$this->db->select('*');
$this->db->from('votes');
$this->db->where('film_id', $film_info->id);
$this->db->where('vote', '1');
$query2 = $this->db->get();
$data['votes_count'] = $query2->num_rows();
}
$this->load->view('template', $data);
This is the code in the model:
<?php
class Home_model extends CI_Model
{
function get_films($limit)
{
$query = $this->db->get('films', $limit, $this->uri->segment(2));
return $query->result();
}
}
And this is the code in the view:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="<?php echo $film['poster_src'] ?>" alt="Film poster">
<div class="caption">
<h3><?php echo $film['title'] ?></h3>
<p>Year: <?php echo $film['year'] ?></p>
<p>Genre: <?php echo $genre_name ?></p>
<p>Votes: <?php echo $votes_count ?></p>
<p>Watch Add to bookmarks</p>
</div>
</div>
</div>
If I put the foreach code in the view, it works properly.
I am not 100% sure so don't vote if false just make me aware i will try another way if possible.in foreach loop try to put the data in another array like this
$new_array[] = $the_result_value_you want
then you will be able to use $new_array outside the loop
I'm pulling comments from MySQL with PDO with a limit of 2 comments to show, yet the query does not retrieve the comments nor can I var_dump neither print_r since it does print anything. I believe it should be an issue with the query itself, thought it hasn't worked for countless hours so I figured I'd ask more experienced programmers.
There is no data outputted onto the page, I'm unsure whether It's an issue with the second_count variable or the post_iD variable.
1. Am I using the while loop correctly?
2. Better to use while loop or foreach?
3. Does var_dump and print_r function not work due to errors in the
query or in PHP.INI from what it seems?
Here is how I'm pulling the data with PDO.
PUBLIC FUNCTION Comments( $post_iD,$second_count ){
if($second_count){
$sth = $this->db->prepare("
SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username, U.photo
FROM comments C, users U
WHERE U.status = '1'
AND C.uid_fk = U.uiD
AND C.msg_id_fk = :postiD
ORDER BY C.com_id ASC LIMIT :second, 2");
$sth->execute(array(':postiD' => $post_iD, ':second' => $second_count));
while( $row = $sth->fetchAll())
$data[] = $row;
if(!empty($data)){
return $data;
}
}
}
And here is how I'm trying to display the information on my page,
<?php
$commentsarray = $Wall->Comments( $post_iD, 0 );
$x=1;
if($x){
$comment_count = count($commentsarray);
$second_count = $comment_count-2;
if($comment_count>2){
?>
<div class="comment_ui" id="view<?php echo $post_iD; ?>">
View all<?php echo $comment_count; ?> comments
</div>
<?php
$commentsarray = $Wall->Comments( $post_iD, $second_count );
}
}
if( $commentsarray ){
foreach($commentsarray as $data){
$com_id = $data['com_id'];
$comment = tolink(htmlcode($data['comment'] ));
$time = $data['created'];
$mtime = date("g:i", $time);
$username = $data['username'];
$com_uid = $data['uid_fk'];
$photo = $data['photo'];
?>
<div class="stcommentbody" id="stcommentbody<?php echo $com_id; ?>">
<div class="stcommentimg">
<img src="<?php echo $photo;?>" class="small_face">
</div>
<div class="stcommenttext">
<?php if($uiD == $com_uid || $uiD == $post_iD ){ ?>
<a class="stcommentdelete" href="#" id="<?php echo $com_id;?>" title="Delete Comment"></a>
<?php } ?>
<div class="stmessage"><?php echo clear($comment); ?></div>
</div>
<div class="stime"><?php echo $mtime;?> — Like</div>
</div>
<?php
}
}
?>
1.Simply like this:
$data = $sth->fetchAll();
if(!empty($data) AND count($data) > 0){
return $data;
}
You don't need while to work with fetchAll.
2.I'ts better to use Exception in every your query then you can see if there is any error.
e.g
try
{
//your PDO stuffs here
}
catch (PDOException $e)
{
echo $e->getMessage();
}