2017-08-30 103 views
1

我想使用select選項來更新表。 這些是代碼,當我嘗試它時,沒有數據顯示到表中。請幫我看看這些代碼。如何使用php和mysql中的select選項更新表

這些代碼用於選擇選項。

<form method="POST"> 
 
      <text class="sort"><span>Course:</span></text> 
 
      
 
      <select class="sel" name="select_course" id="select_course"> 
 
       <?php 
 
       $query=mysqli_query($conn,"select DISTINCT Course from `tbl_student`"); 
 
\t \t   while($row=mysqli_fetch_array($query)){ 
 
\t \t \t  ?> 
 
       <option><?php echo $row['Course'];?></option> 
 
       <?php 
 
        } 
 
       ?> 
 
      </select> 
 
      <input class="btnsearch" type="button" name="submit" value="Search"> 
 
      <input class="btn" type="button" name="btn_add" value="Add Student"> 
 
      <input class="btn_import" type="button" name="import" value="Import File"> 
 
      

而這些代碼是用於顯示數據,以表。

<?php 
 
          echo '<table> 
 
         <tr> 
 
         <td>name</td> 
 
         <td>Id number</td> 
 
         <td>Course</td> 
 
         <td>School Year</td> 
 
         <td>Semester</td> 
 
         </tr>'; 
 
        if(isset($_POST['submit'])) 
 
        { 
 
         $result2 = mysqli_query($conn, "Select name,id_number,Course,school_year,semester from tbl_student where Course='".$_POST['select_course']."'"); 
 
          
 
         while($row=mysqli_fetch_row($result2)){ 
 
          echo '<tr> 
 
         <td>'.$row["name"].'</td> 
 
         <td>'.$row["id_number"].'</td> 
 
         <td>'.$row["Course"].'</td> 
 
         <td>'.$row["school_year"].'</td> 
 
         <td>'.$row["semester"].'</td> 
 
         </tr>'; 
 
         } 
 
          echo '</table>'; 
 
        } 
 
        ?> 
 
       
 
      </form>

我想要的是當我從選擇選項的表格會自動更新選擇。

+0

沒有ajax和onchange事件,你不能根據選擇的變化來做到這一點,你必須提交一個表單POST到php – clearshot66

+0

您的代碼容易受到[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻擊。您應該通過[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https ://secure.php.net/manual/en/pdo.prepared-statements.php)驅動程序。 [**這篇文章**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)有一些很好的例子。 –

回答

0

做到這一點,最好的辦法是ajaxjs這裏沒有標記,這樣你就可以用HTML和PHP一樣做到這一點:

<form action="updateData.php"> 
    <select name="select_course" onchange="this.form.submit()"> 

onchange="this.form.submit()"將提交時選擇更改爲updateData.php的形式,把代碼來更新表格中的數據。

0
while($row=mysqli_fetch_row($result2)){ 

這是你的代碼錯誤。你正在使用mysqli_fetch_row,並且正在使用$ row [「name」]。只需使用mysqli_fetch_assoc然後使用$ row [「name」]。如果你將使用mysqli_fetch_row那麼你必須把數據索引放在數據庫中