How to add multiple selection checkboxes to mysql db? - php

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

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.

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...?

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

Related

Insert Checkbox Array into Multiple MySQL table Columns with PHP

I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table. I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:
$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
$check = $_POST['check'];
if($check){
print_r($check);
}else{
echo "nothing checked";
}
for($i=0;$i<sizeof($check);$i++){
$query = "INSERT INTO `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)";
$result = mysqli_query($connection,$query);
if(!$result){
die("NOPE <br>" . mysqli_error($connection));
}else{
echo "yup";
}
}
}
And here is the HTML
<form action="" method="post>
<input type="checkbox" name="check[]" value="check1">Check1
<input type="checkbox" name="check[]" value="check2">Check2
<input type="checkbox" name="check[]" value="check3">Check3
<input type="submit" value="submit">
</form>
The MySQL Columns are "id, check1, check2, check3" so SQL should look like:
INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`)
VALUES (NULL, 'test', 'test', 'test');
Appreciater outside P.O.V. that I need thanks!
If you the execute the query inside the loop, you would be executing x number of queries (or inserting x number of rows) rather than inserting into x number of columns. There is really no need to use a loop here since you have a set number of columns.
Use echo statements to print out the queries to see what you are running and you'll see why this isn't working.
You also should never put user input directly into a MySQL query. Read up on SQL injections.

While loop - Only one input from many others is sending a value through POST

This is the code where I get my input names and values from a table called optionale and doing something with these:
<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus">
<?php } ?>
</form>
The optionale table looks like this:
The HTML looks like this:
As you can see in the last picture, I have in HTML, a name for input (taken from optionale table) and the actual input in which I write a value.
fisa-init.php:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
$bucata = mysqli_real_escape_string($mysqli, $_POST['nrBucati']);
$cod = mysqli_real_escape_string($mysqli, $_POST['codProdus']);
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
$mysqli->close();
In the code above (fisa-init.php) I am trying to take all the input values from my HTML and update rows in another table called stocuri:
As you can see, only the second row from stocuri table was updated, but I wrote values in all 5 inputs. It got only the last input.
How to modify the while loop in order to take all my inputs value?
If something is not clear, I apologize a hundred times. I will explain all the informations that are needed.
P.S. cod in table optionale is the same with cod in table stocuri. In this way, I know where to update values.
Each <input> MUST have an individual name or a named array.
So give each an aditional number like name1,name2 or use an named array like name[]
Finally this name="codProdus[]" is your solution.
Read more here
HTML input arrays
Have a nice day

send array[] from php to mysql

im working on a project but first i would to understand one thing.
i have 2 input type text field with name="firstname[]" as an array (in the example im working with no jquery but it will be generated dinamically with it) and cant make it to mysql.
here is what i have: index.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname[]"> <br>
Firstname 2: <input type="text" name="firstname[]">
<input type="submit">
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO input_field (firstname)
VALUES
('$_POST[firstname]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
the question is: how can i send the firstname[] array to the mysql database?
thanks for your time
This should work:
//Escape user input
$names = array_map('mysql_real_escape_string', $_POST[firstname]);
//Convert array to comma-delimited list
$names = rtrim(implode(',', $names), ',');
//Build query
$sql="INSERT INTO input_field (firstname) VALUES ('$names')";
Note: In general, it's better to use parameterized queries than mysql_real_escape_string(), but the latter is much safer than no escaping at all.
The following should generate the SQL statement you need. Remember to use mysql_escape_string before putting it into your database, though! Or even better, use PDO and bind the values. :)
$values = array();
$sql = "INSERT INTO table (firstname) VALUES ";
foreach ($_POST['firstname'] as $name) {
$values[] = "('".mysql_real_escape_string($name)."')";
}
$sql .= implode(",", $values);

how do you store multiple rows and column array in mysql

I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}

Parse CSV From HTML form and Insert into MYSQL Database

I'm trying to take an array and insert it into seperate rows in a MYSQL database.
Basically, there's an HTML form for a top 5 list that I want to input in one field, but with each value seperated by commas. So, for example (Artist 1, Artist 2, Artist 3, etc.)
These 5 values then have to be seperated into 5 values that are then inserted into 5 rows in a MYSQL database.
So the HTML form looks like this:
<tr>
<td>Loud Rock</td>
<td><label for="lr_topfive"><input type="text" placeholder="" name="lr_topfive" size="75"
maxlength="100" autofucus required /></label></td>
</tr>
and the form value is sent to another php file with this code in it:
$val = $_POST['lr_topfive'];
$data = str_getcsv($val);
??????
$lr_one = mysql_prep($_POST['lr_one']);
$lr_two = mysql_prep($_POST['lr_two']);
$lr_three = mysql_prep($_POST['lr_three']);
$lr_four = mysql_prep($_POST['lr_four']);
$lr_five = mysql_prep($_POST['lr_five']);
$query = "INSERT INTO xyz_wb (lr_one, lr_two, lr_three, lr_four, lr_five) VALUES ('{$lr_one}','{$lr_two}', '{$lr_three}', '{$lr_four}', '{$lr_five}')";
$result = mysql_query($query, $connection);
if ($result) {
redirect_to("email-ready.php");
} else {
//display error message
echo "<p>Yikes!</p>";
echo "<p>" . mysql_error() . "</p>";
}
I get that the 'lr_topfive' value is parsed and seperated into distinct values by the first two lines, but I dont know what to do before inserting these values into the MYSQL DB.
I think you are just looking for:
$top_five_array = explode(',', $_POST['lr_topfive']);
and then:
$lr_one = mysql_prep($top_five_array[0]);
$lr_two = mysql_prep($top_five_array[1]);
....
However, this will break if there are not exactly 4 comma's in your input field.
Apart from that you need to switch to prepared statements using PDO or mysqli, see the comments below your question.

Categories