getActorsList() is a method from db_functions. It gets names from database. The option echo works perfectly for them.
<?php
include("scripts/db_functions.php");
include("scripts/queries.php");
?>
<form method="post" accept-charset="utf-8">
<h2>When does the show start where
<label>
<select name="who">
<?php
echo '<option value="0">---Choose an actor---</option>';
$names = getActorsList();
while ($row = mysqli_fetch_assoc($names)) {
echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
}
mysqli_free_result($names);
?>
</select>
</label>
is playing?
<input class="forminput" type="submit" value="Search" style="display: inline-block">
</h2>
</form>
<table>
<tr>
<th>Channel</th>
<th>Starts</th>
<th>Title</th>
<th>More information</th>
</tr>
<?php
$dbrow = query1();
while ( ($oneRow = mysqli_fetch_assoc($dbrow))!= null) {
echo '<tr>';
echo '<td>' . $oneRow["channelName"] . '</td>';
echo '<td>' . $oneRow["start"] . '</td>';
echo '<td>' . $oneRow["title"] . '</td>';
echo '<td>' . $oneRow["moreInfo"] . '</td>';
echo '</tr>';
}
?>
</table>
queries.php:
<?php
function query1() {
include_once("db_functions.php");
if (!($conn = db_connect())) {
return false;
}
if (empty($_POST["who"])) {
$clear_who = "";
} else {
$clear_who = htmlspecialchars($_POST["who"]);
}
$result = mysqli_query($conn, "SELECT * FROM broadcasts WHERE broadcasts.title IN (SELECT shows.title FROM shows, roles WHERE shows.title = roles.title AND shows.moreInfo = roles.moreInfo AND roles.name = '".$clear_who."')");
if (!$result) {
die(mysqli_error($conn));
}
mysqli_close($conn);
return $result;
}
My only problem is when I choose an actor's name and I click on submit, the selected option is always the first one. How can I change the selected option, that I last sent in POST method?
CodePudding user response:
You can compare the current name in the row to the posted value (if it exists)
Change
echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
to
echo '<option value="'.$row["name"].'"'.(isset($_POST["who"]) && $_POST["who"] == $row["name"] ? " selected " : "").'>'.$row["name"].'</option>';
This will add the selected
attribute to the option if the name the option is for matches the posted value.