繁体   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