Emmanuel Daniel Emmanuel Daniel - 23 days ago 7
MySQL Question

PHP/MYSQL display mysql record age using datediff

I'm new to PHP/MYSQL, I'm trying to display the age of all records from my database using

DATEIFF
as shown in the line 17 of my code, but it just won't work. I need somebody to help me out with this.

$result = mysqli_query($con,"SELECT * FROM growers");

echo "<table class='table table-striped table-advance table-hover'>
<tbody>
<tr>
<th><i class='icon_profile'></i>&nbsp;Batch</th>
<th><i class='icon_ol'></i>&nbsp;Date Received</th>
<th><i class='icon_clock_alt'></i>&nbsp;Age when Received</th>
<th><i class='icon_clock_alt'></i>&nbsp;Current Age</th>
<th><i class='icon_star'></i>&nbsp;NO of Birds</th>
<th><i class='icon_info'></i>&nbsp;View More</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>" . $row['BATCH'] . "</td>";
echo"<td>" . $row['BIRTH DAY'] . "</td>";
echo"<td>" . $row['AGE'] . "&nbsp;Week(s)" . "</td>";
echo"<td>" . "SELECT DATEDIFF("NOW()", "$row['BIRTH DAY']") AS CURRENT AGE". "</td>";
echo"<td>" . $row['NO OF BIRDS'] . "</td>";
echo"<td>" . $row['AGE'] . "</td>";
echo"</tr>";
}
echo "</table>";

mysqli_close($con);
?>

Answer

You could select in main select

  $result = mysqli_query($con,
         "SELECT 
        growers.BATCH, 
        growers.`BIRTH DAY`, 
        growers.AGE,            
        DATEDIFF(NOW(),growers.`BIRTH DAY`) AS CURRENT_AGE,
        growers.`NO OF BIRDS`            
        FROM growers; "
   );


                        echo "<table class='table table-striped table-advance table-hover'>
                         <tbody>
                      <tr>
                         <th><i class='icon_profile'></i>&nbsp;Batch</th>
                         <th><i class='icon_ol'></i>&nbsp;Date Received</th>
                         <th><i class='icon_clock_alt'></i>&nbsp;Age when Received</th>
                         <th><i class='icon_clock_alt'></i>&nbsp;Current Age</th>
                         <th><i class='icon_star'></i>&nbsp;NO of Birds</th>
                         <th><i class='icon_info'></i>&nbsp;View More</th>
                      </tr>";

                        while($row = mysqli_fetch_array($result))
                        {
                         echo"<tr>";
                         echo"<td>" . $row['BATCH'] . "</td>";
                         echo"<td>" . $row['BIRTH DAY'] . "</td>";
                         echo"<td>" . $row['AGE'] . "&nbsp;Week(s)" . "</td>";
                         echo"<td>" . $row['CURRENT_AGE'] . "</td>";
                         echo"<td>" . $row['NO OF BIRDS'] . "</td>";
                         echo"<td>" . $row['AGE'] . "</td>";
                         echo"</tr>";
                        }
                        echo "</table>";

                        mysqli_close($con);
                        ?>