2012-12-14 60 views
0

如何將html表單放入PHP while循環中?在PHP while循環中的HTML表單

它認爲這樣的事情,但它不工作:

<?php 

$i=1; 
while ($i<=5){ 

<form name="X" action="thispage.php" method="POST"> 
    <input type="text"> 
    <input type="submit"> 
</form>; 

$i=$i+1; 

       } 

?> 
+0

什麼「不起作用」?結果是什麼?你期望什麼? – deceze

回答

0

你可以通過與?>的HTML之前關閉你的PHP代碼塊,然後你的代碼的其餘部分之前<?php重啓。

個人而言,我更喜歡在PHP中使用echo HTML。它使你的代碼更具可讀性。此外,我建議使用for循環,而不是你在那裏。

<?php 
for ($i=1; $i<=5; $i++) { 
    echo '<form name="x" action="thispage.php" method="POST">', 
     '<input type="text" name="trekking">', 
     '<input type="submit"', 
     '</form>'; 
} 
?> 
+0

我傾向於在打開和關閉以及回顯之間來回翻轉,但我使用回顯的問題無法使用Notepad ++的打開/關閉標籤查找功能。 –

+0

@RickCalder,這是一個偏好問題。對我而言,以編程方式使用的HTML並不重要,所以我對此沒有任何問題。我也傾向於首先使用HTML,然後使用PHP來處理動態部分。我也經常使用模板引擎。 – Brad

+0

@Brad在模板引擎上的任何建議? – Bizarre

2

您可以使用echo

<?php 

$i=1; 
while ($i<=5){ 

    echo ' 
     <form name="X" action="thispage.php" method="POST"> 
      <input type="text" name="trekking"> 
      <input type="submit"> 
     </form>; 
    '; 

    $i=$i+1; 
} 
?> 

或以其他方式打開和關閉PHP標籤:

<?php 

$i=1; 
while ($i<=5){ 

//closing PHP 
?> 

     <form name="X" action="thispage.php" method="POST"> 
      <input type="text" name="trekking"> 
      <input type="submit"> 
     </form>; 

<?php 
//opening PHP 

    $i=$i+1; 
} 
?> 
+1

「極品」是一個強大的詞 – Sharlike

+0

所以真實:)更新。 – Alvaro

3
<?php 

$i=1; 
while ($i<=5):?> 

<form name="X" action="thispage.php" method="POST"> 
     <input type="text" name="trekking"> 
    <input type="submit"> 
</form> 

<?php $i=$i+1; 

    endwhile; 

?> 

使用endwhile使PHP和HTML的一個不錯的可讀性分離。 如果不需要,不要回顯代碼塊。

5

你可以,你就是不能在PHP中間有這樣的原始HTML。在HTML之前結束PHP語句,然後像這樣重新打開它:

<?php 

$i=1; 
while ($i<=5){ 
?> 

<form name="X" action="thispage.php" method="POST"> 
    <input type="text" name="trekking"> 
<input type="submit"> 
</form> 

<?php 
    $i=$i+1; 
    } 

?> 
+0

輕微的錯字問題。 '$ i'增量在php標籤之外。 :) – NemesisX00

+0

更正,謝謝。 –

+0

謝謝大家。 Rick Calder的代碼效果最好。不知道PHP可能會被HTML中斷,然後繼續進行,就好像什麼都沒發生過一樣。 – TavernSenses

0

您應該首先學習PHP。你想要實現的是非常簡單的基本PHP。

但回答你的問題在while循環內回聲"[form-html goes here]";。一定要逃脫所有其他"

+0

no no no no no。你不應該回應該HTML。 – thatidiotguy

0

如果你的目標是試圖輸出5形成具有相同名稱(這我不會擺在首位推薦),你可以試試這個:

$i=1; 
$strOutput = ""; 
while ($i<=5){ 

$strOutput .= '<form name="X" action="thispage.php" method="POST">'; 
    $strOutput .= '<input type="text" name="trekking">'; 
    $strOutput .= '<input type="submit">'; 
$strOutput .= '</form>'; 

    $i=$i+ 
} 

echo $strOutput; 

決不 PHP代碼中使用HTML像你在你的問題中所做的那樣。

0
<?php 

$i=1; 
echo"<form name="X" action="thispage.php" method="POST">"; 
while ($i<=5) 
{ 
    echo"<input type="text">"; 
    echo"<input type="submit">"; 
    $i++; 
} 
echo"</form>"; 

?>