2011-12-31 115 views
-4

我將整個HTML內容放入PHP變量中,並在該內容中嘗試回顯從數據庫獲取的某些數據。但問題是我無法進行數據庫查詢和回顯reuslt,因爲整個事情都是用PHP和HTML封裝的(如果聽起來令人困惑,請查看下面的代碼。)如何在使用PHP封裝HTML時在HTML內寫入PHP

有什麼辦法可以讓數據庫在PHP變量之外查詢並回顯它。儘管我已經試過查詢變量之外的數據庫,但是這次發現>>$row['examdate']正在創建這個問題。它顯示一個語法錯誤。

我正在做所有這些使用DOMPDF生成PDF。獲取變量後,我將它傳遞給我的控制器來生成pdf。

<?php $variable= " I need your help, I want to echo this <br> 

<table id=\"table-6\" width=\"100%\"> 
<tr> 
    <th>Exam Date</th> 
    <th>Exam Type</th> 
    <th>Subject</th> 

</tr> 

$this->db->select('*'); 
$this->db->from('marks'); 
$this->db->where('studentid', $studentid); 
$this->db->where('examdate >=', $daterange1); 
$this->db->where('examdate <=', $daterange2); 
$this->db->order_by('examdate','DESC'); 
$query = $this->db->get(''); 


      if ($query->num_rows() > 0) 
      { 
       $row = $query->row_array(); 

    <tr> 
     <td> echo $row['examdate']</td> ///****this line***** 

     <td>12</td> 
     <td>12</td> 
     <td>100</td> 
    </tr> 
    </table> 
    "; ?>-<< variable ends here 
+0

好奇你是怎麼不工作的代碼,這樣巨量?爲什麼作爲一個新手,你不檢查它是否在每行之後都有效?!?!?!?!在這種情況下,你只有一行你有問題,但現在你有20 – zerkms 2011-12-31 07:03:56

+0

使用[HEREDOC語法](http://www.php.net/manual/en/language.types.string.php# language.types.string.syntax.heredoc)用於大型字符串變量。 – mario 2011-12-31 07:07:42

+0

可能的重複[是否有理由在PHP中使用Heredoc?](http://stackoverflow.com/questions/5673269/is-there-a-reason-to-use-heredoc-in-php) – mario 2011-12-31 07:09:28

回答

3

您需要將變量的填充從你的PHP邏輯的分離執行。

在稍後階段附加數據,而不是嘗試在一個步驟中分配所有內容。

下面是修改後的代碼:

<?php 
$variable = " I need your help, I want to echo this <br> 

<table id=\"table-6\" width=\"100%\"> 
    <tr> 
     <th>Exam Date</th> 
     <th>Exam Type</th> 
     <th>Subject</th> 

    </tr> 
"; 

// now execute the database logic 
$this->db->select('*'); 
$this->db->from('marks'); 
$this->db->where('studentid', $studentid); 
$this->db->where('examdate >=', $daterange1); 
$this->db->where('examdate <=', $daterange2); 
$this->db->order_by('examdate','DESC'); 
$query = $this->db->get(''); 

if ($query->num_rows() > 0) 
{ 
    $row = $query->row_array(); 

    // append the data to the existing variable using ".=" 
    // and include the examdate 
    $variable .= " 
     <tr> 
      <td>{$row['examdate']}</td> ///****this line***** 

      <td>12</td> 
      <td>12</td> 
      <td>100</td> 
     </tr> 
    "; 
} 

// append the closing table tag to the variable using ".=" again 
$variable .= "</table>"; 

// output $variable 
echo $variable; 

>

+0

感謝favo。您的解決方案正是我一直在尋找的。它完美的作品。再次感謝Favo。 :) – 2011-12-31 15:40:04

+0

第三個支架在這裏是關鍵點... :) – 2011-12-31 15:41:38