mardi 26 avril 2016

How to add multiple selection checkboxes to mysql db?

I want the user be able to check multiple checkboxes, after which his/hers selection is printed on the html page and add each selection to my Mysql db. Unfortunately I only see the literal string 'Array' being added to my db instead of the selected names.

My script looks as follows:

    <html>
<head>
<title>checkbox help</title>
</head>
<?php
if (isset($_POST['submit'])) {
    $bewoner_naam = $_POST["bewoner_naam"];
    $how_many = count($bewoner_naam);
    echo 'Names chosen: '.$how_many.'<br><br>';
    if ($how_many>0) {
        echo 'You chose the following names:<br>';
    }
    for ($i=0; $i<$how_many; $i++) {
        echo ($i+1) . '- ' . $bewoner_naam[$i] . '<br>';
    }
        echo "<br><br>";
}

$bewoner_naam = $_POST['bewoner_naam']; echo $bewoner_naam[0]; // Output will be the value of the first selected checkbox echo $bewoner_naam[1]; // Output will be the value of the second selected checkbox print_r($bewoner_naam); //Output will be an array of values of the selected checkboxes

$con = mysql_connect("localhost","usr","root"); mysql_select_db("db", $con); $sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('$_POST[bewoner_naam]')";

if (!mysql_query($sql,$con))

{

die('Error: ' . mysql_error());

}

echo "1 record added";

mysql_close($con)

?>

<body bgcolor="#ffffff">
<form method="post">
Choose a name:<br><br>
<input type="checkbox" name="bewoner_naam[]" value="kurt">kurt <br>
<input type="checkbox" name="bewoner_naam[]" value="ian">ian <br>
<input type="checkbox" name="bewoner_naam[]" value="robert">robert <br>
<input type="checkbox" name="bewoner_naam[]" value="bruce">bruce<br>
<input type="submit" name = "submit">
</form>
</body>
<html>

Thank you so much with helping me!!!

Kindest regards,

Martin




Aucun commentaire:

Enregistrer un commentaire