I have radio buttons and check boxes that I am trying to submit into a MySQL database using PHP. My issue is that these are going into junction forms and I also need to include the text inserts as a value on the table. Also, I honestly don't think I'm doing the radio buttons and check boxes right, something about Boolean structure?
I'm using MySQLi and just Notepad++.
My insert page has some radio buttons:
<input type="radio" name="audience" value="Youth" />Youth
<input type="radio" name="audience" value="Teen" />Teen
<input type="radio" name="audience" value="Adult" />Adult
and some check boxes:
<tr><td><input type="checkbox" name="genre" value="1" />Action </td>
<td><input type="checkbox" name="genre" value="2" />Adventure </td></tr>
<tr><td><input type="checkbox" name="genre" value="3" />Comedy</td>
<td><input type="checkbox" name="genre" value="4" />Coming of Age</td></tr>
This is the PHP I have for the radio buttons:
if (isset($_POST['submit'])){
$audience= $_POST['audience'];
$sql = "INSERT INTO series (series_target_audience) VALUES
('$audience')";
}
This code claims that it is working at this moment, but it is currently not actually depositing the values into the database at all.
You need to open a connection to MySQLi and then prepare the statement, bind parameter and execute it.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
if(isset($_POST['submit'])){
$possibleRadioValues = ['Youth', 'Teen', 'Adult'];
if(in_array($_POST['audience'], $possibleRadioValues, true)){
$stmt = $mysqli->prepare('INSERT INTO series (series_target_audience) VALUES (?)');
$stmt->bind_param('s', $_POST['audience']);
$stmt->execute();
}
}
Also worth noting is that you should validate the data coming from your HTML form, as it might not be what you expect. In this case I used a white list of values in the array.