PHP如何在数据库中保存复选框值?

时间:2011-11-15 00:34:36

标签: php sql checkbox

我有复选框表,我从数据库中检索:

<?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表格中,无论选中多少次复选框,我都会得到一行。

那么这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西:

$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());
}