Comments not displaying when called from Database inside While Loop - php

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();
}

Related

In database table there is no rows means getting error Undefined variable: results using codeigniter

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();
}

PHP link same page with link and send data via $_POST

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...
}
?>

foreach() return a null value

I have another error anymore, when I try to display a result in my view, the result is NULL and I can't see the result of my query at models.
Here's my code list :
on the controller (home.php) :
$data['hasil5'] = $this->home_model->popular_list();
on the model (home_model.php) function popular_list() :
function popular_list($limit=2)
{
$this->db->select('news.*');
$this->db->where('id',$this->uri->segment(3));
$this->db->where('publish',1);
$this->db->where('viewed >= ',5);
$this->db->order_by('id','DESC');
$this->db->limit($limit);
$query = $this->db->get('news');
return $query->result();
} //thanks to kumar_v
and on my view (home.php) as a part of "Popular news" :
<h2>Most Popular News :</h2>
<?php
foreach ($hasil5 as $data5):
?>
<div class="welcome clear"><img class="imgl" src="<?php echo base_url(); ?>assets/news/original/<?php echo $data5->image; ?>" alt="" height="119" width="125" />
<div class="fl_right">
<h2><?php echo anchor($data5->kategori.'/detail/'.$data5->id,$data5->title) ?></h2>
<p><?php echo $data5->sinopsis; ?></p>
</div>
</div>
<?php
endforeach;
?>
The results is NULL, can you correct it again? thanks..
try this :
function popular_list($limit = 2) {
$query = $this->db->select('*')
->where('id',$this->uri->segment(3))
->where('publish',1)
->where('viewed >= ',5)
->order_by('id','DESC')
->limit($limit)
->get('news');
print_r($query->result());
return $query->result();
}
You can put the whole thing in $query variable. And also, you can improve your $this->db->where() by putting the params in an array.
You should fix your code to look like so:
<?php
foreach ($data['hasil5'] as $data5):
?>
You were using the wrong variable in your foreach loop.
Checking if the query will return any row is a good idea.
function popular_list($limit=2)
{
$result = null;
$this->db->select('news.*');
$this->db->where('id',$this->uri->segment(3));
$this->db->where('publish',1);
$this->db->where('viewed >= ',5);
$this->db->order_by('id','DESC');
$this->db->limit($limit);
$query = $this->db->get('news');
if($query->num_rows() > 0)
{
$result = $query->result();
}
return $result;
}

A variable won't display

I have code that runs a query on the database and returns some data and displays it.
All very simple. I've tested the query and it work's perfectly.
So somewhere between the query being executed and me displaying the data, it's not working.
$q = "SELECT u.username, r.position, r.score, r.winner, t.team FROM ".TBL_FOOT_TOUR_ROUNDS." r
LEFT JOIN ".TBL_USERS." u ON u.id = r.winner
LEFT JOIN ".TBL_FOOT_TOUR_PLAYERS." pl ON pl.userid = r.winner
LEFT JOIN ".TBL_FOOT_TEAMS." t ON t.id = pl.team
WHERE r.tourid = '$tour_id' && r.round = '$i' ORDER BY r.position";
$result = $database->query($q);
?>
<div class="vertical-holder">
<div class="vertical-header"><p><?php echo $roundName[$i]; ?></p></div>
<?php
while($row=mysql_fetch_assoc($result)){
extract($row);
if($k&1){
?>
<div class="horizontal-holder<?php echo $j; ?>">
<div class="white-holder">
<div class="player-holder">
<?php
if($winner == 0){
echo "<p>TBC</p>";
}
else{
echo "<p><a href='/profile.php?id=$winner'>$username</a><br />$team</p>";
}
?>
</div>
<div class="score-holder">
<?php
if($score == NULL){
echo "<p>-</p>";
}
else{
echo "<p>$score</p>";
}
?>
</div>
</div>
<?php
}
That's the snippet of code that's (what I believe to be) relevant.
The score is showing as '-' all the time even when a score is present.
The rest of the returned data shows no problem.
Can anyone see why the score variable isn't showing?
Thanks
<?php
if($score == NULL){
echo "<p>-</p>";
} else {
echo "<p>$score</p>";
}
?>
you got it wrong. if the value in the database is null, $score will not be null, it will be the string "null". so try
<?php
if(strtoupper($score) === "NULL"){
echo "<p>-</p>";
} else {
echo "<p>$score</p>";
}
?>
:)
alternatively you can create some utility function that changes a variable:
function nullify(&$data) {
if(strtoupper($data) === "NULL") {
$data = NULL;
}
}
and then call it like this:
nullify($score);
if $score should be set to null, it will be null after the call. then you can keep your logic the way it is ^^
Not sure what $score contains, but it seems to me that you could write your test like:
if($score < -1){ // or $score <= -1
echo "<p>-</p>";
}
else{
echo "<p>$score</p>";
}

Codeigniter table Join then Display Tags Problem

I have a problem that concerns blog posts and displaying the tag words from another table.
I seem to be able to pull the info out of the tables fine, however when I try to display the posts and the tags, I get one tag per post. In other words if I have 7 tags for a post, I get 7 iteration's of that post each with one tag instead of 1 post with 7 tags.
My Controller ( do have a question about the $this->db->get(posts, tags) is that correct
$this->db->order_by('posts.id', 'DESC');
$where = "publish";
$this->db->where('status', $where);
$this->db->join('tags', 'tags.post_id = posts.id');
$this->db->limit('7');
$query = $this->db->get('posts', 'tags');
if($query->result())
$data = array();
{
$data['blog'] = $query->result();
}
$data['title'] = 'LemonRose';
$data['content'] = 'home/home_content';
$this->load->view('template1', $data);
The view.
$limit = 5; // how many posts should we show in full?
$i = 1; // count
foreach ($blog as $row):
$permalink = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
$url = CompressURL ("$permalink");
$description = $row->title . $row->post;
$twittermsg = substr($description, 0, 110);
$twittermsg .= "...more " . $url;
if ($i < $limit) // we are under our limit
{ ?>
<div class="titlebox">
<div class="title"><? echo ucwords($row->title); ?></div>
<span><? echo $row->date, nbs(10), $row->author; ?></span>
</div>
<div class="clear"></div>
<? $str = str_word_count($row->post, 0);
if ($str >= 500) {
$row->post = html_entity_decode($row->post);
$row->post = $this->typography->auto_typography($row->post); // display?>
<div class="split"> <? echo $row->post = word_limiter($row->post, 480); ?>
<div class="tags"><? echo $row->tag; ?></div>*** These 3 lines seem to be where I am confused and getting the wrong display
<p><h3>More <?php echo anchor("main/blog_view/$row->id", ucwords($row->title)); ?> </h3></p>
<p>Trackback URL: <? echo base_url() . "trackbacks/track/$row->id"; ?></p>
<!-- tweet me -->
<?echo anchor("http://twitter.com/home?status=$twittermsg", 'Tweet'); ?>
This is my first attempt with join and I have very little experience getting the display with implode, if that is the right way to go.
Thank you in advance.
Try
<div class="tags"><? echo implode(', ', $row->tag); ?></div>
and remove the 2 rows before this one.

Categories