简体   繁体   中英

PHP how to save checkbox value in database?

I have table with checkboxes, which I retrieve from 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>   ';    
     }
}
?>

I want to save the results in database:

  • Table: places
  • Columns: places_id , book_id , shop_id

However, I can't get it to work right. In shop_id column I get the same number as many times as checkboxes are checked.

If I'm using this:

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

In places table I get just one row no matter how many times checkboxes are checked.

So what is the correct way to do that?

I think this is what you're looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM