Php – Adding binary checkbox values to MySQL database using PHP

binarycheckboxdatabasemysqlphp

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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Create your news page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
        <fieldset>
            <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">
                <br>
                <span class="label">Footer</span>
                <input type="checkbox" name="footer" value="FOOTER">

                <hr>
                <span class="label">Local news</span>
                <input type="checkbox" name="local" value="LOCALNEWS">
                <br>
                <span class="label">National news</span>
                <input type="checkbox" name="national" value="NATIONALNEWS">
                <br>
                <span class="label">International news</span>
                <input type="checkbox" name="international" value="INTERNATIONALNEWS">
                <p>
                <input type="submit">
            </form>
        </fieldset>
    </body>
</html>

And the PHP document is written as follows:

<?php
    $user="user_***";
    $password="*********";
    $database="dbxyz";
    mysql_connect("localhost", $user, $password);
    mysql_select_db($database, $db_handle);
    mysql_select_db("dbxyz");
    if(isset($_POST['layout']))
    {
        foreach($_POST['layout'] as $value {
            $insert="INSERT INTO layout (header, footer, local, national, international) VALUES ('$value')";
            mysql_query($insert);
        }
    }
?>

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.