2011-11-15 50 views
0

我有一个复选框,这是我从数据库中检索表:PHP如何保存数据库中的复选框值?

<?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表我得到的只是一排,无论复选框被检查了多少次。

那么正确的做法是什么?

回答

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

谢谢!你是金子! – Lina

相关问题