Jump to content

[Ask] [CodeIgniter] empty array


Orasion

Recommended Posts

Hi again all, once again I need your help.

I try to fetch data from my database which doesnt have any result yet. I want it to echo "No result" if there is no data from database.

My code is

 

<?php foreach($comment->result_array() as $comment) {?>
	<p><?php echo $comment['text']; ?></p>
<p><i><?php echo $comment['author']; ?></i></p>
	<?php } ?>

 

I tried to insert

 

<?php if(!empty($comment)) {
//above code

} else {
echo "No result"; }
?>

 

but no output have been printed. Can you give me a hint to echo empty array like this one?

Thanks

Link to post
Share on other sites

I'm a bit confused here, does the full code look like this

 

<?php if(!empty($comment->result_array())) { ?>	
	<?php foreach($comment->result_array() as $comment) {?>
	<p><?php echo $comment['text']; ?></p>
<p><i><?php echo $comment['author']; ?></i></p>
	<?php } ?>
	<?php } else {?>
	<?php echo "No result"; ?>
	<?php } ?>

 

cos its error and output nothing.

Or did i do wrong?

Link to post
Share on other sites

Try running your foreach loop using the result() function instead of result_array()

if(!empty($comment->result())) { 
     foreach ($comment->result() as $comment) {
     // rest of code here

 

If you read codeigniters user guide you'll find result_array() expects ONLY results as an array so if you have 1 or less results it's going to throw an error.

 

The result() function can handle arrays but doesn't require them

Link to post
Share on other sites

thanks mike, maybe I should read user guide before posting here :)

btw, I follow your suggestion code but have no output with that, I think its still error but then I follow the 2nd example in this page

 

http://codeigniter.com/user_guide/database/results.html

 

and finally showing result that I want

 

:)

Link to post
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.