dorflv5944 2015-07-19 20:15
浏览 81
已采纳

创建一个包含多个复选框的数组

I have multiple checkboxes where the user should check the series he watches. In my database i want to update the column "watch" with the value "yes" in every series he checked (i have already created a column with all the series in it).

The HTML code:

<p>Please check the series you watch:</p>
<form action="2.php" method="post">
Game Of Thrones <input type="checkbox" value="Game Of Thrones" name="series"/><br>
The Big Bang Theory <input type="checkbox" value="The Big Bang Theory" name="series"/><br>
Arrow <input type="checkbox" value="Arrow" name="series"/><br>
<input type="submit" value="Submit">
</form>

The send.php:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$series = $_POST['series'];
$sql = "UPDATE data SET watch='yes' WHERE series='$series'";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

It works as long as the user check only one series, but when he check two or more it updates only one of the series he checked.

Help?

  • 写回答

4条回答 默认 最新

  • douya7309 2015-07-19 20:29
    关注

    Change your HTML code like:

    <p>Please check the series you watch:</p>
    <form action="2.php" method="post">
      <!-- make the name as an array -->
        Game Of Thrones <input type="checkbox" value="Game Of Thrones" name="series[]"/><br>
        The Big Bang Theory <input type="checkbox" value="The Big Bang Theory" name="series[]"/><br>
        Arrow <input type="checkbox" value="Arrow" name="series[]"/><br>
        <input type="submit" value="Submit">
    </form>
    

    And your send.php :

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "test";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    
    $series = $_POST['series'];
    for( $i = 0; $i < count($series); $i ++) {
    
      $sql = "UPDATE data SET watch='yes' WHERE series='$series[$i]'";
    
      if ($conn->query($sql) === TRUE) {
         echo "Record updated successfully";
      }  
      else {
         echo "Error updating record: " . $conn->error;
      }
    }
    $conn->close();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable