2013-11-01 89 views
0

我有這個代碼,我想防止表頭重複。 有人可以幫忙嗎?本網站要求我提供更多細節,然後才能發佈此問題。表頭在while循環中重複

if (isset($_POST['toys'])) { 
$query = 'SELECT * FROM `toys` WHERE size = ?'; 
$sth = $db->prepare($query); 
foreach($_POST['toys'] as $each_check) { 
    if(! $sth->execute(array($each_check))) { 
     die('MySQL Error: ' . var_export($sth->error_info(), TRUE)); 
    } 

    echo "<table>"; 
    echo "<tr> 
      <th>ratio</th> 
      <th>size</th> 
      <th>built</th> 
      <th>description</th>    
      </tr>"; 

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { 

     echo "<tr><td>" . $row['ratio'] . 
      "</td><td>" . $row['size'] . 
      "</td><td>" . $row['built'] . 
      "</td><td>" . $row['description'] . 
      "</td></tr>"; 
    } 
    echo "</table>"; 
    } 
} 

坦克

回答

0

<table>標籤之前foreach

echo "<table>"; 
echo "<tr> 
    <th>ratio</th> 
    <th>size</th> 
    <th>built</th> 
    <th>description</th>    
    </tr>"; 

foreach($_POST['toys'] as $each_check) { 
    if(! $sth->execute(array($each_check))) { 
     die('MySQL Error: ' . var_export($sth->error_info(), TRUE)); 
    } 
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { 

     echo "<tr><td>" . $row['ratio'] . 
      "</td><td>" . $row['size'] . 
      "</td><td>" . $row['built'] . 
      "</td><td>" . $row['description'] . 
      "</td></tr>"; 
    } 
} 

// And then echo it after foreach 

echo "</table>"; 
0

因爲你是呼應在foreach.So將重複表頭當迭代外occusrs..Try它循環。

if (isset($_POST['toys'])) { 
$query = 'SELECT * FROM `toys` WHERE size = ?'; 
$sth = $db->prepare($query); 

//Open the table before loop 
echo "<table>"; 
    echo "<tr> 
      <th>ratio</th> 
      <th>size</th> 
      <th>built</th> 
      <th>description</th>    
      </tr>"; 
foreach($_POST['toys'] as $each_check) { 
    if(! $sth->execute(array($each_check))) { 
     die('MySQL Error: ' . var_export($sth->error_info(), TRUE)); 
    } 

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { 

     echo "<tr><td>" . $row['ratio'] . 
      "</td><td>" . $row['size'] . 
      "</td><td>" . $row['built'] . 
      "</td><td>" . $row['description'] . 
      "</td></tr>"; 
    } 
    } 
    //Close the table after the loop 
    echo "</table>"; 
} 
0

修改代碼如下

if (isset($_POST['toys'])) { 
    $query = 'SELECT * FROM `toys` WHERE size = ?'; 
    $sth = $db->prepare($query); 
    echo "<table>"; 
    echo "<tr> 
      <th>ratio</th> 
      <th>size</th> 
      <th>built</th> 
      <th>description</th>    
      </tr>"; 
    foreach ($_POST['toys'] as $each_check) { 
     if (!$sth->execute(array($each_check))) { 
      die('MySQL Error: ' . var_export($sth->error_info(), TRUE)); 
     } 

     while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { 

      echo "<tr><td>" . $row['ratio'] . 
      "</td><td>" . $row['size'] . 
      "</td><td>" . $row['built'] . 
      "</td><td>" . $row['description'] . 
      "</td></tr>"; 
     } 
    } 
    echo "</table>"; 
} 
+0

非常感謝你親愛的人! – Paco