I am trying to use a checkbox to populate a single string in a database with specific formatting. I can successfully print the array, but I don't understand how to assign this to a variable in order to connect to the database and to use again elsewhere on the site. Here is the html:
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="C">Commercials
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="CP">Commercial Print
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="V">Voice Overs
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="X">Background Work
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="F">Film
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="TV">Television
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="BT">Business Theatre Industrials
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="I">Film Industrials
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="MV">Music Videos
PHP:
foreach($_POST['bookCodes'] as $codes) {
print "(".$codes.")";
};
I want the printed string to equal $bookCodes
. I have tried putting the array in a function but then I get the first value only. Here is that code:
function prepBookCodes ($value)
{
if (isset($_POST[$value])) {
foreach ($_POST[$value] as $codes) {
return "(" . $codes . ")";
}
}
}
$bookCodes = prepBookCodes('bookCodes');
print $bookCodes;
Any help would be greatly appreciated!
Concatenation is the answer. Make your function return something please!
function prepBookCodes ($value)
{
if (isset($_POST[$value])) {
foreach ($_POST[$value] as $codes) {
$string .= "(" . $codes . ")";
}
}
return $string;
}
$bookCodes = prepBookCodes('bookCodes');
Your first declaration doesn't have it as an array:
<input type="checkbox" id="bookCodes" name="bookCodes" value="C">Commercials
Should be
<input type="checkbox" id="bookCodes" name="bookCodes[]" value="C">Commercials
function prepBookCodes ($value)
{
if (isset($_POST[$value])) {
foreach ($_POST[$value] as $codes) {
echo "(" . $codes . ")";
}
}
}
Maybe you can concatenate the post values into a single variable $bookCodes
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['bookCodes'])) {
$bookCodes = '';
foreach ($_POST['bookCodes'] as $codes) {
$bookCodes .= "(" . $codes . ")";
}
print $bookCodes;
}
}
If you for example check all the checkboxes, the $bookCodes
variable will contain:
(C)(CP)(V)(X)(F)(TV)(BT)(I)(MV)