簡體   English   中英

PHP如何在數據庫中保存復選框值?

[英]PHP how to save checkbox value in database?

我有復選框表,我從數據庫中檢索:

<?php
$result = mysql_query("SELECT shop_id, name FROM shop") or die(mysql_error());

if(mysql_num_rows($result) > 0)
{
    while($row = mysql_fetch_assoc($result)) 
    {
        echo '<tr> 
                  <td>
                      <input type="checkbox" name="identifer[]" value="'.$row['shop_id'].'" /> <br />
                  </td>  
                  <td>'.ucfirst($row['shop']).'</td> 
              </tr>   ';    
     }
}
?>

我想將結果保存在數據庫中:

  • 表: places
  • 列: places_idbook_idshop_id

但是,我無法讓它正常工作。 shop_id列中,我檢查復選框時獲得的次數相同。

如果我使用這個:

$identifer = $_POST['identifer'];
if( count( $identifer) > 1)
{
    foreach($identifer as $x)
    {
        $y .= $x.",";
        $val = rtrim($y,",");
        $q2 = "INSERT INTO places (places_id, book_id, shop_id) VALUES (NULL, '$book_id', '$val')";
        $result2 = mysql_query($q2) or die(mysql_query());
    }
}

places表格中,無論選中多少次復選框,我都會獲得一行。

那么這樣做的正確方法是什么?

我想這就是你要找的東西:

$identifier = $_POST['identifer']; // Also, you spelled identifier wrong ;)
// There's no guarantee that you were given an array for identifier
if( is_array( $identifier) && count( $identifier) > 1)
{
    $values = array();
    // This creates a bunch of insert values
    foreach($identifier as $x)
    {
        $values[] = "(NULL, '$book_id', '$x')";
    }

    // Join all those values together into one SQL query (this will generate multiple rows)
    $q2 = "INSERT INTO places (places_id, book_id, shop_id) VALUES " . implode( ', ', $values);
    $result2 = mysql_query($q2) or die(mysql_query());
}

暫無
暫無

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

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