PHP 遇到 $Error 时不显示网格

PHP To Not Display Grid if $Error Is Hit

我有下面的语法,它应该可以正常工作,并且在按钮按下事件上将首先验证开始日期和结束日期是否已输入到文本框中,如果其中一个是空白,则消息写入屏幕通知用户它是空的。

我的语法的问题是,即使错误消息显示在屏幕上,语法继续迭代并且 table 的 header 行仍然显示(我假设如果查询return 数据 table 也会填充数据)。应该如何更改此语法,以便在屏幕上显示错误时,一旦错误显示在屏幕上,代码就会停止?

<?php  
if(isset($_POST['submit'])){

$begindateerror = false;
$enddateerror = false;
if (empty($_POST['begindate'])) {
$begindateerror = true;
}
if (empty($_POST['enddate'])) {
$enddateerror = true;
}

if ($begindateerror) {
echo "<strong>Please select a begin date.</strong><br>";
} else { }
if ($enddateerror) {
echo "<strong>Please select a end date.</strong><br>";
} else { }

$option = array();

//Build option array for connection string

$db = JDatabase::getInstance( $option );
$tsql = $db->gettsql(true);
$tsql = "SQL tsql"; 

$db->settsql($tsql); 
$tsql = $db->loadObjectList();

$numofrows = mssql_num_rows($tsql);

?>
<table border="1">
<thead>
<tr>
//Create Header Row for the table
</tr>
</thead>
<tbody>
<?php
foreach( $tsql as $result ) { 
print "<tr>";
//write the query results to the table
print "</tr>";
}}?>

您可以将后面的所有代码放在 else 括号内的错误之后,然后让 PHP 回显 header:

<?php
if(isset($_POST['submit'])){
  $begindateerror = false;
  $enddateerror = false;
  if (empty($_POST['begindate'])) {
    $begindateerror = true;
  }
  if (empty($_POST['enddate'])) {
    $enddateerror = true;
  }
  if ($begindateerror) {
    echo "<strong>Please select a begin date.</strong><br>";
  } else if ($enddateerror) {
    echo "<strong>Please select a end date.</strong><br>";
  } else {
    $option = array();
    //Build option array for connection string
    $db = JDatabase::getInstance( $option );
    $tsql = $db->gettsql(true);
    $tsql = "SQL tsql";
    $db->settsql($tsql);
    $tsql = $db->loadObjectList();
    $numofrows = mssql_num_rows($tsql);
    echo '<table border="1"><thead><tr></tr></thead><tbody>';
    foreach( $tsql as $result ) {
      print "<tr>";
      //write the query results to the table
      print "</tr>";
    }
  }
}
?>