Reputation:
I have a table in MySQL and I want to check in PHP whether there are any 'tasks' written (it's a todo list webapp). If there aren't I want to display a message 'You haven't added any tasks yet', problem is it's not displaying.
PHP is assuming that the list of tasks is never empty, when for user 1 (in PHP current user_id = 2), for instance, it is, since I haven't inserted any tasks in my MySQL for User 1 (all tasks are user 2).
<?php
global $connection;
$user = $_SESSION['user_id'];
$query = "SELECT * FROM to_do_list WHERE user = $user";
$items = mysqli_query($connection, $query);
?>
<div>
<?php if(!empty($items)): ?>
<ul id="myUL">
<?php foreach($items as $item): ?>
<li>
<span class="item<?php echo $item['done'] ? ' done' : '' ?>"><?php echo $item['task']; ?></span>
<?php if(!$item['done']): ?>
<a href="#" class="donebutton">Done</a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>You haven't added any tasks yet.</p>
<?php endif; ?>
</div>
Upvotes: 0
Views: 234
Reputation: 1806
mysqli_query returns a "resource" not an array - so:
instead of foreach($items as $item):
use while($item = mysqli_fetch_assoc($items))
and now every $item
is an associated array of results (meaning - you can call the output using it's name like $item['done']
)
also - instead of if(!empty($items))
you should use if(mysqli_num_rows($items) > 0)
Upvotes: 2