Funkcja do generowania pól wyboru (checkbox) dla wybranych opcji z podanej tablicy. Podczas dodawania nowego wpisu do bazy danych, wynikiem będzie ciąg znaków zawierający opcje z tablicy oddzielone przecinkiem, np. "1,5,9" lub "high,low,middle"; dlatego musisz ustawić kolumnę bazy danych jako VARCHAR lub coś w tym rodzaju.
Funkcja
Funkcja służy trzem celom:
- Wyświetlanie pól wyboru (checkbox) podczas dodawania nowego wpisu do bazy danych.
- Wyświetlanie pól wyboru (checkbox) z wcześniej wybranymi opcjami podczas edytowania wpisów.
- Wyświetlanie zwykłej zawartości (ciągu znaków) na stronie internetowej podczas prezentowania danych pobranych z bazy danych.
<?php
/**
* Print out checkboxes for selecting options.
*
* This function generates checkboxes for selecting options from a provided array.
* It also checks the checkboxes if the option IDs are present in the $dbEntry string.
*
* @param string $name The name attribute for the checkboxes.
* @param array $checkboxArray An associative array of option IDs and names.
* @param bool $printCheckbxs (Optional) Indicates whether to print checkboxes or just output names.
* @param string $dbEntry (Optional) A comma-separated string of option IDs stored in the database.
* If provided, checkboxes for corresponding option IDs will be checked.
*/
function printCheckboxes($name, $checkboxArray, $printCheckbxs = true, $dbEntry = '')
{
// If $dbEntry is not empty, parse it into an array of option IDs
$array_ids = !empty($dbEntry) ? explode(',', $dbEntry) : [];
// Get the keys of the checkbox array
$checkboxKeys = array_keys($checkboxArray);
// Initialize an array to store option names (if $printCheckbxs = false)
if (!$printCheckbxs) {
$justNames = [];
}
// Iterate over each option in the checkbox array
foreach ($checkboxArray as $output_id => $output_name) {
// Check if the option ID is in the $array_ids array
$checked = in_array($output_id, $array_ids) ? 'checked' : '';
if ($printCheckbxs) {
// Create a checkbox for the option
echo '<label><input type="checkbox" name="' . $name . '[]" value="' . $output_id . '" ' . $checked . '> ' . $output_name . '</label>';
} else {
// Store the option name for later use
$justNames[] = $checked ? $output_name : '';
}
}
// If not printing checkboxes, output the names separated by commas
if (!$printCheckbxs) {
// Filter out empty names and concatenate them with commas
$names = array_filter($justNames);
echo implode(', ', $names);
}
}
Użycie
Dodawanie nowego wpisu:
<?php
// Wywołanie funkcji do generowania pól wyboru
printCheckboxes('features', $featuresArr, true);
Edytowanie istniejącego wpisu:
<?php
// Wywołanie funkcji do generowania pól wyboru z wcześniej wybranymi opcjami
printCheckboxes('features', $featuresArr, true, $row['features']);
Wyświetlanie wyników z bazy danych:
<?php
// Wyświetlenie zwykłej zawartości (ciągu znaków) na podstawie danych z bazy danych
printCheckboxes('features', $featuresArr, false, $row['features']);