【问题标题】:PHP how to save checkbox value in database?PHP如何将复选框值保存在数据库中?
【发布时间】:2011-11-15 09:00:39
【问题描述】:

我有一个带有复选框的表格,我从数据库中检索到:

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

那么正确的做法是什么?

【问题讨论】:

    标签: php sql checkbox


    【解决方案1】:

    我想这就是你要找的东西:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多