0

I'm trying to identify whether I am looking at the first column in the array.

I haven't tried anything, but googled plenty and cannot find a solution.

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $col) {
        if () //NEED CODE HERE
        echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
    }
    echo '</tr>';
}
Geshode
  • 3,600
  • 6
  • 18
  • 32
  • 2
    I suggest looking at `$row`, to see how you would be able to get the values of each column per row – Carl Binalla Oct 15 '19 at 04:07
  • Possible duplicate of [How to determine the first and last iteration in a foreach loop?](https://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop) – Minuddin Ahmed Rana Oct 15 '19 at 04:53

1 Answers1

0

mysqli_fetch_row fetches "one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero)." So the key of the column is the same as column order.

So you can do this:

while($row = mysqli_fetch_row($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 0) {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

But column is subjected to changes in database structure and SQL query changes. I would personally prefer mysqli_fetch_assoc or mysqli_fetch_object so I can use the column by name instead of order number. Its less error prone. For example,

while($row = mysqli_fetch_assoc($sql)) {
    echo '<tr>'; 
    foreach ($row as $key => $col) {
        if ($key === 'ip_address') {
          echo "<td><a href = 'https://whatismyipaddress.com/ip-lookup' target = '_blank'>$col</a></td>";
        }
    }
    echo '</tr>';
}

Note: $sql here should be a mysqli_query result instead of the actual SQL string.

Koala Yeung
  • 7,475
  • 3
  • 30
  • 50