Php – Adding binary checkbox values to MySQL database using PHP


I'm new to PHP, and I am creating a basic CMS using PHP and MySQL. I'm struggling to get the checkbox information from my HTML page across into the database.

How can I make the values to appear as binary 0 or 1 values?

The HTML document is written as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <title>Create your news page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            <legend>Checked components will show in the page</legend>
            <form method="POST" action="http://*********.php">
                <span class="label">Header</span>
                <input type="checkbox" name="header" value="HEADER">
                <span class="label">Footer</span>
                <input type="checkbox" name="footer" value="FOOTER">

                <span class="label">Local news</span>
                <input type="checkbox" name="local" value="LOCALNEWS">
                <span class="label">National news</span>
                <input type="checkbox" name="national" value="NATIONALNEWS">
                <span class="label">International news</span>
                <input type="checkbox" name="international" value="INTERNATIONALNEWS">
                <input type="submit">

And the PHP document is written as follows:

    mysql_connect("localhost", $user, $password);
    mysql_select_db($database, $db_handle);
        foreach($_POST['layout'] as $value {
            $insert="INSERT INTO layout (header, footer, local, national, international) VALUES ('$value')";

Best Solution

You are supposed to put all the values in the query at once.
It can be done like that:

$values = array(
    'header'        => null,
    'footer'        => null,
    'local'         => null,
    'national'      => null,
    'international' => null

foreach (array_intersect_key($_POST, $values) as $key => $value) {
    $values[$key] = mysql_real_escape_string($value);

mysql_query("INSERT INTO layout (header, footer, local, national, international) VALUES ('$values[header]', '$values[footer]', '$values[local]', '$values[national]', '$values[international]')");

Also, notice the mysql_real_escape_string call. It escapes all the characters of its parameter that can be used for SQL injections.