Jane Jane - 2 months ago 5
PHP Question

Cant echo date null field

I am currently using php to connect the tables in my ms sql database to appear on my webpage.The table appears however im having issues with the date fields that are null in my sql table.

The table is a garage repair for vehicles.

create table [VEHICLE_STATUS](
[STATUS_ID] [int] identity (1,1) not null,
[VEHICLE_ID] [INT] not null,
[REPAIR_START_DATE] [DATE] not null,
[REPAIR_END_DATE] [DATE] not null,
[DESCRIPTION] [nvarchar] (200) not null
);


However not all the vehicles are in for repair thus have no repair start or end dates.

I have tried to change the date fields to change to "available" instead of null

The error that comes up is;


Fatal error: Call to a member function format() on null in
C:\xampp\htdocs\view.php on line 57


<?php
$server = "\SQLEXPRESS";
$options = array( "Database"=>"test" );


$conn = sqlsrv_connect( $server, $options );


if( !$conn ) die( print_r( sqlsrv_errors(), true ) );

$query = "select * from VW_VEHICLE_STATUS";
$sql = sqlsrv_query($conn, $query);


echo "<table >";
echo "<tr>";
echo "<td style='border:1px solid black;Font-size=18;Font-weight=bold'>";
echo "MAKE";
echo "</td>";
echo "<td style='border:1px solid black;Font-size=18;Font-Weight=bold'>";
echo "MODEL";
echo "</td>";
echo "<td style='border:1px solid black;Font-size=18;Font-Weight=bold'>";
echo "REGISTRATION";
echo "</td>";
echo "<td style='border:1px solid black;Font-size=18;Font-Weight=bold'>";
echo "REPAIR_START_DATE";
echo "</td>";
echo "<td style='border:1px solid black;Font-size=18;Font-Weight=bold'>";
echo "REPAIR_END_DATE";
echo "</td>";
echo "<td style='border:1px solid black;Font-size=18;Font-Weight=bold'>";
echo "DESCRIPTION";
echo "</td>";
echo "</tr>\n";

while ($row = sqlsrv_fetch_array($sql))
{
echo "<tr>";
echo "<td style='border:1px solid black'>";
echo $row['MAKE'];
echo "</td>";
echo "<td style='border:1px solid black'>";
echo $row['MODEL'];
echo "</td>";
echo "<td style='border:1px solid black'>";
echo $row['REGISTRATION'];
echo "</td>";
echo "<td style='border:1px solid black'>";
echo $row['REPAIR_START_DATE']->format("Y-M-d");
echo "</td>";
echo "<td style='border:1px solid black'>";
echo $row['REPAIR_END_DATE']->format("Y-M-d"); ;
echo "</td>";
echo "<td style='border:1px solid black'>";
echo $row['DESCRIPTION'];
echo "</td>";
echo "</tr>\n";
}
echo "</table>";

sqlsrv_close( $conn);
?>

Answer

Try to check if the value is an instance of DateTime before calling format method on it.

echo $row['REPAIR_END_DATE'] instanceof DateTime ? $row['REPAIR_END_DATE']->format('Y-m-d') : '';