The Solution
The actual solution here is only 4 new lines of code.
Before the while loop, we declare a variable called $count
, which will hold which iteration we are on in the loop.
$counter = 0;
At the end of the loop, but before closing it, we add 1 to the $counter
variable, this means 1 will be added for every iteration in the loop.
$counter++;
Now, we just surround the delete <a>
element with an IF statement, checking if $counter
is not 0. If $counter
is anything except 0, it will show the link.
if($counter != 0) {
echo "<a href='itemdelete.php?delete={$id}'>Delete</a>";
}
MAJOR SECURITY RISK
I can not stress enough how insecure your query is.
Little Bobby says you may be at risk for SQL Injection Attacks. Learn about Prepared Statements with parameterized queries. I recommend PDO
, which I wrote a class for to make it extremely easy, clean, and more secure than using non-parameterized queries. Also, This article may help you choose between MySQLi
and PDO
It is very important that you fix this security issue, no matter how big your application is (or is not). I highly urge you to fix this for this query, and any other queries you may have in your application AS SOON AS POSSIBLE.
Above, I linked to a PDO class that I made. PDO
is generally a better tool than mysqli_*
, as it supports many different types of databases. I believe it is more highly regarded by a lot of developers. Even if you do not with to use my class or another class, I highly recommend you switch over to PDO
anyways.
Complete code
<ul>
<?php
require('connect.php');
$gettheid = $_GET['id'];
//this query has some serious security risks, anyone can alter a $_GET variable to be anything
//meaning they can interact with your database in ways you did not want. Including deleting any row
//or even entire tables easily.
$query = "SELECT * FROM `shoppinglist` WHERE items='".$gettheid."'";
//the actual solution is a counter, so you need to create a variable to hold how many rows you have gone through.
$counter = 0;
if ($result = $conn->query($query)) {
while($row = $result->fetch_object()){
$id = $row->srno;
$item = $row->items;
$image = $row->image;
?>
<li>
<div class="intheline">
<?php
//if counter is not 0, display the delete link
if($counter != 0) {
echo "<a href='itemdelete.php?delete={$id}'>Delete</a>";
}
?>
</div>
<div class="thumbnail intheline">
<img src="photo/<?php echo $image; ?>" />
</div>
<div class="intheline">Name of the item: <?php echo $item; ?></div>
</li>
<?php
//add 1 to $counter for every iteration, so only the first iteration it will be equal to 0.
$counter++;
}
}
?>
</ul>