Tuesday, January 25, 2022

[FIXED] What is the best way to write heredocs in php and how to keep function max 20 lines

Issue

Following is the code of Class Admin that contains two method

listRecord();
Details($id);

The code is working fine but i don't like this code because function is huge and coupled and i don't want to use heredocs in function Kindly guide me what is the best way to write heredocs and how to separate heredocs in separate function.

Admin Class

Class Admin{

   public function listRecord() {

    $query = "select Report_type, Report_Id, Report_Reults,Patient_name, Patient_Address, "
            . "Patient_Phone from Patient join Reports "
            . "on Patient.Patient_ID = Reports.Patient_ID ";

    $result = $this->conn->query($query);

    if ($result->num_rows > 0) {
        // output data of each row

        echo <<<HTML

        <h2>Report's Data</h2>
    <table>
    <tr>
        <th>Patient Name</th>
        <th>Patient Address</th>
        <th>Patient Phone</th>
        <th>Report Type</th>
        <th>Report Results</th>
    </tr>
<tr>
HTML;
        while ($row = $result->fetch_assoc()) {
            echo"       
<tr>
<td>  $row[Patient_name]    </td>
<td>  $row[Patient_Address] </td>
<td>  $row[Patient_Phone]   </td>
<td>  $row[Report_type]     </td>
<td>  $row[Report_Reults]   </td>

<td><a href='../Admin/AdminData.php?del_id=$row[Report_Id]'>Delete</a></td>
<td><a href='../Admin/AdminData.php?report_id=$row[Report_Id]'>Details</a></td>

</tr>";
        }
        echo "</table>";
    }
}

}


  public function Details($id) {

    $this->data_id = $id;

    $query = "select Report_type, Report_Id, Report_Reults,Patient_name, Patient_Address, "
            . "Patient_Phone from Patient join Reports WHERE "
            . "Reports.Report_Id=$this->data_id and Patient.Patient_ID=$this->data_id ";

    $result = $this->conn->query($query);



    if ($result->num_rows > 0) {
        // output data of each row

        echo <<<HTML

        <h2>$row[Patient_name] Data</h2>
    <table>
    <tr>
        <th>Patient Name</th>
        <th>Patient Address</th>
        <th>Patient Phone</th>
        <th>Report Type</th>
        <th>Report Results</th>
    </tr>
<tr>
HTML;
        while ($row = $result->fetch_assoc()) {

            echo"       
<tr>
<td>  $row[Patient_name]    </td>
<td>  $row[Patient_Address] </td>
<td>  $row[Patient_Phone]   </td>
<td>  $row[Report_type]     </td>
<td>  $row[Report_Reults]   </td>

</tr>";
        }
        echo "</table>";
    }
}

Solution

Try saving the HTML for both functions in different files and including them when required. You could use .phtml format for these files, which is HTML with some PHP.

if ($result->num_rows > 0) {
    require_once FILE_PATH; // Path to the specific file needed in the function.
}


Answered By - Condorcho

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.