簡體   English   中英

提交多個復選框值到數據庫

[英]Submitting Multiple Checkboxes Values to Database

我對PHP很陌生,正在尋找一種將多個復選框的值提交到數據庫中的方法! 現在,如果數據庫中的值= 1,我已經設法使復選框顯示為“已檢查”,否則將取消選中該復選框。

下面是我當前的代碼。

<?php
    $query = "SELECT * FROM users_achievements_xbox WHERE user_id = '$userID' && game_id = '$gameID' ORDER BY achievement_id ASC";
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result)) {   // Start looping table row
    $userID = $row['user_id'];
    $gameID = $row['game_id'];
    $achievementID = $row['achievement_id'];
    $achievementName = $row['achievement_name'];
    $achievementDescription = $row['achievement_description'];
    $achievementValue = $row['achievement_value'];

    $check = mysql_query("SELECT * FROM users_achievements_xbox WHERE user_id = '$userID' && game_id = '$gameID' && achievement_id = '$achievementID'");
    $row2 = mysql_fetch_assoc($check);
    $achievement_locked = $row2['achievement_locked'];

    if($achievement_locked == "0")
    {
        $checked = 'checked="checked"';
    }
    else
    {
        $checked = "";
    }
?>
    <tr align="center" bgcolor="#eeeeee">
        <td> <img src="images/achievements/<?php echo $gameID; ?>/<?php echo $achievementID; ?>.jpg" /> </td>
        <td> <?php echo $achievementName; ?> </td>
        <td> <?php echo $achievementDescription; ?> </td>
        <td> <?php echo $achievementValue; ?> </td>
        <td> <input type="checkbox" name="checkbox" value="0" <?php echo $checked ?> /> </td>
    </tr>

<?php
} // end of while loop
?>

我當時正在考慮通過isset嘗試執行此操作,但我不希望使用環狀的Submit按鈕,我似乎無法找到如何將Checkbox包裹在表單中的方法,但是當我以這種方式快速對其進行測試時,“ achievement_locked”中的每個值如果我只希望將選中的復選框更改為0(如果未選中)則為1,則數據庫中的“”變為0!

謝謝你的幫助!

這是一個例子。 獲得理解。 我沒有轉義POST變量。 確保你這樣做。

HTML檔案:

<form name="form1" method="post" action="test.php">
  <p>
    <input name="colors[]" type="checkbox" id="colors[]" value="0">
    Red 
    <input name="colors[]" type="checkbox" id="colors[]" value="0">
    Blue 
    <input name="colors[]" type="checkbox" id="colors[]" value="0">
    Green</p>
  <p> 
    <input name="colors[]" type="checkbox" id="colors[]" value="0">
    Yellow 
    <input name="colors[]" type="checkbox" id="colors[]" value="0">
    Brown </p>
    <input type="submit">
</form>

這是您的php文件應具有的內容。

<?php

$colors = $_POST['colors'];

$red = isset($colors[0]) ? 1 : 0;
$blue = isset($colors[1]) ? 1 : 0;
$green = isset($colors[2]) ? 1 : 0;
$yellow = isset($colors[3]) ? 1 : 0;
$brown =isset($colors[4]) ? 1 : 0;



// query
$sql = "INSERT INTO table (red,blue,green,yellow,brown) VALUES (:red,:blue,:green,:yellow,:brown)";
$q = $conn->prepare($sql);
$q->execute(array(':red'=>$red,
                    ':blue'=>$blue,
                    ':green'=>$green,
                    ':yellow'=>$yellow,
                  ':brown'=>$brown));
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM