0

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?

1 Answer 1

2

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.