Trying to Find a Loop to use for a specific MySQL query I'm trying to see if there is a loop I can use in order to pull off this code a little more elegantly. I was previously using a foreach($row as $cell) with $row = mysqli_fetch_row($result) but because of that I couldn't access the data from the 'user' column in order to check it against the session variables in the if statment. Here's the code:

$sql = "SELECT * FROM tbl_name ORDER BY subject, description LIMIT {$startpoint},{$limit}";
$result = $mysqli-&gt;query($sql);
$num_rows = mysqli_num_rows($result);

if($num_rows&gt;0){
$field_num = $mysqli-&gt;field_count;
echo "&lt;h1&gt;HERE ARE SOME RESULTS:&lt;/h1&gt;";
echo "&lt;table border='0'&gt;";    

while($row = mysqli_fetch_array($result))
{
    echo"&lt;tr&gt;";
    echo"&lt;td&gt;".$row['subject']."&lt;/td&gt;";
    echo"&lt;td&gt;".$row['description']."&lt;/td&gt;";
    echo"&lt;td&gt;".$row['user']."&lt;/td&gt;";
    if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
    echo"&lt;td&gt;You can delete this&lt;/td&gt;";
    }
    else{
    echo"&lt;td&gt;Code didn't work&lt;/td&gt;";
    }
    echo "&lt;/tr&gt;\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no results!';
}
?&gt;


Is there a loop I can run that can also allow me to access data from each row so I don't have to print out a new line of code for each column but keep the if statement in tact? Thanks!
Saving lines of code in search of elegance is not always (in fact hardly ever in my experience) a worthwhile exercise if it comes at the expense of clarity and maintainability. Your current code is better than any solution that iterates over table columns because it is clear and easy to change. For example, combining the data of two columns into one or changing column order are both trivial.

You might consider moving this display logic to a template. Here is an example of a twig template:

{% if results %}
&lt;h1&gt;HERE ARE SOME RESULTS&lt;/h1&gt;
&lt;table&gt;
    {% for row in results %}
    &lt;tr&gt;
        &lt;td&gt;{{ row.subject }}&lt;/td&gt;
        &lt;td&gt;{{ row.description }}&lt;/td&gt;
        {% if row.user == user %}
        &lt;td&gt;You can delete this&lt;/td&gt;
        {% else %}
        &lt;td&gt;Code didn't work&lt;/td&gt;
        {% endif %}
    &lt;/tr&gt;
    {% endfor %}
&lt;/table&gt;
{% else %}
&lt;p&gt;No results&lt;/p&gt;
{% endif %}


The PHP becomes very simple:

$bindings = array(
    'results' =&gt; $mysqli-&gt;query('SELECT...'),
    'user' =&gt; $_SESSION['firstname'] . ' ' . $_SESSION['lastname']
);
$twig-&gt;render('template.html', $bindings);