Reputation: 2156
I have the following query
<?php
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
?>
<?php while ($row = mysql_fetch_assoc($result)) { ?>
if first row, add id = "thumb1"
<a id="thumb1" href='address' onclick="...">
<img src='<?php echo 'Index_Images/image_thumb_' . $row['IMG_IDENTIFIER'] . '.jpg'; ?>' />
</a>
<?php else ?>
<a id="others" href='address' onclick="...">
<img src='<?php echo 'Index_Images/image_thumb_' . $row['IMG_IDENTIFIER'] . '.jpg'; ?>' />
</a>
<?php
}
?>
I want to know how to test for the first row in mysql_fetch_assoc
, if that is possible.
Thank you.
Upvotes: 0
Views: 928
Reputation: 1482
Try:
// ...
$first = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
// code with thumb1
} else {
// code with others
}
$first = false;
}
// ...
or even better when it comes to the complexity of code:
// ...
$first = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
// code with thumb1
$first = false;
continue;
}
// code with others
}
// ...
Also I would consider using PDO or mysqli or some ORM instead of mysql.
If you will put params into query in future remember of escaping - not esacping is one of the most common ways to have sql injection vulnerability with mysql in php.
Upvotes: 3
Reputation: 27082
Use variable $i
, which is incremented in each loop.
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
if ($i == 0) {
echo 'first row';
}
echo ...;
$i++;
}
Upvotes: 3
Reputation: 1817
<?php
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$i = 1;
?>
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if($i == 1) {
if first row, add id = "thumb1"
<a id="thumb1" href='address' onclick="...">
<img src='<?php echo 'Index_Images/image_thumb_' . $row['IMG_IDENTIFIER'] . '.jpg'; ?>' />
</a>
<?php }else{ ?>
<a id="others" href='address' onclick="...">
<img src='<?php echo 'Index_Images/image_thumb_' . $row['IMG_IDENTIFIER'] . '.jpg'; ?>' />
</a>
<?php
}
$i++;
}
?>
Check this, if it works.
Upvotes: 1