1

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

GAMITG
  • 3,810
  • 7
  • 32
  • 51
Martin
  • 11
  • 2
  • 1
    **WARNING**: If you're just learning PHP, please, do not learn the obsolete [`mysql_query`](http://php.net/manual/en/function.mysql-query.php) interface. It's awful and has been removed in PHP 7. A replacement like [PDO is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) and a guide like [PHP The Right Way](http://www.phptherightway.com/) helps explain best practices. Your user parameters are **not** [properly escaped](http://bobby-tables.com/php) and this has [SQL injection bugs](http://bobby-tables.com/) that can be exploited. – tadman Apr 26 '16 at 07:59

3 Answers3

0

You can't insert an array into a singular column, it will show up as "array" as you're observing, so you've got two choices:

  • Insert multiple rows, one for each item, by looping over that array.
  • Combine them together using implode into a singular value.

The way your database is structured in your example it's not clear which of these two would be best.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

Since $_POST['bewoner_naam'] is an array, you have to add each item in that array to the database. You can for example use a for loop for this:

$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);

foreach($_POST['bewoner_naam'] as $naam) {
    $sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('". mysql_real_escape_string($naam) ."')";
}

Note that I've used the mysql_real_escape_string function. You will ALWAYS want to include this. For the why and how, see: Sanitizing PHP/SQL $_POST, $_GET, etc...?

Community
  • 1
  • 1
Marijn van Vliet
  • 5,239
  • 2
  • 33
  • 45
  • Dear Rodin, thanks again for your latest remark. Unfortunately as a newbee I got rather confused. For now I have tried to incorporate your first remark and update the code to the latest standard (I hope). But on execution I only get a blank screen and php checkers provide me with the following errors I can seem to figure out :-( – Martin Apr 27 '16 at 11:22
  • Error: There are 2 more opening parenthesis '(' found This count is unaware if parenthesis are inside of a string (!mysqli_query($sql)) { die('Error: ' . mysqli_error(()); } mysqli_close($con); ?>

    ('Error: ' . mysqli_error(()); } mysqli_close($con) Parse error: syntax error, unexpected '$statement' (T_VARIABLE) in your code on line 38 $statement = $conn->prepare($sql); PHP Syntax Check: Errors parsing your code

    – Martin Apr 27 '16 at 11:23
  • Thank you so much again for helping me out!! – Martin Apr 27 '16 at 11:39
  • if the result is just an empty page, this means there is an error somewhere, but PHP is configured to hide this error. Do you have a php.log file somewhere? The location of this file depends on whether you are running the webserver yourself or if you are using someone elses. – Marijn van Vliet Apr 27 '16 at 13:22
  • I do not know. I use someone elses (a hosting provider) – Martin Apr 27 '16 at 16:16
  • I did find this log: – Martin Apr 27 '16 at 16:19
0

First thing is to avoid all mysql_* functions in PHP. They are deprecated, and removed in newer versions, and to top it all of, insecure. I advise you switch to PDO and use prepared statements.

This will not solve your issue however. The issue you are having is that in the code where you combine the SQL you are concatenating the array with the string, that's why you only insert "Array". If you wish to insert all array items as a string, then you need to implode the array:

$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES (:checkboxes)";
$statement = $pdo->prepare($sql);
$statement->bindValue(":checkboxes", implode(",", $_POST["bewoner_naam"]);
$statement->execute();

Although, storing multiple values as a comma separated list in a database is not such a good idea, since it can become too un-maintainable through time, and produces more difficulty when obtaining such data, because you need to "re-parse" it after retrieving it from data.

As @Rodin suggested, you will probably want to insert each array item as a separate row, so I propose the following:

$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES "
    . rtrim(str_repeat('(?),', count($_POST["bewoner_naam"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach ($_POST["bewoner_naam"] as $bewoner_naam) {
    $statement->bindValue($count++, $bewoner_naam);
}
$statement->execute();

This way you will create a bulk insert statement, with as many placeholders as there are selected checkboxes, and put each of their values on a separate line in the database.

For more on PDO, and parameter binding please refer to http://www.php.net/pdo

slax0r
  • 688
  • 4
  • 8
  • 2
    Storing multiple values in a database by imploding might not be a good idea... @Martin do you want each 'bewoner' (=inhabitant) to be added as a new row? – Marijn van Vliet Apr 26 '16 at 08:06
  • @Rodin that's true, but it seems it's what he is trying to do. – slax0r Apr 26 '16 at 08:09
  • Rodin and SlaxOr, first of all thanks for the PDO suggestion and your examples!!! I indeed wanted each 'bewoner' to be added as row :-) – Martin Apr 26 '16 at 12:47