I have created a drop down list that is populated by data from mysql db, im trying to save the selected value in a session variable but im not sure how to write this (where the *** are)? And does it need to be posted to server side eve though its all in php?
<?php
$servername1 = "localhost";
$username1 = "root";
$password1 = "";
$dbname1 = "gpdb1";
$conn1 = new mysqli($servername1, $username1, $password1, $dbname1);
if ($conn1->connect_error) {
die("connection failed: " . $conn1->connect_error);
}
$sql2 = "SELECT DoctorID, Title, Surname FROM doctors";
$result2 = $conn1->query($sql2);
echo "<select name='doctor' value=''><option>Select a Doctor</option>";
if ($result2->num_rows > 0) {
foreach($result2 as $row2)
{echo "<option value=".$row2['DoctorID'].">".$row2['Title']." ".$row2['Surname']."</option>";
}
}echo "</select>";
$_SESSION['selected']=***;
if (isset($_SESSION['selected'])){
echo $SESSION['selected'];}
?>
Thanks :)
First, I advise you to indent your code, for better readability !
The HTML attribute "value" in your tag isn't useful, you can remove it.
And then, it is not useful to control your session field with isset() since you're setting it just above.
I think that you just need to control if the given value in the post field is correct.
The line you are looking for is :
$_SESSION['selected'] = $_POST['doctor'];
First enable your error reporting:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
Then you should set all relevant tags in your html code properly, but for this to work you need "name" tag on select element. Then make sure that your html code when script is executed looks something like this(
<!DOCTYPE html>
<html>
<body>
<form action="do_stuff.php">
<select name="doctor">
<!-- your loop generates this part -->
<option value="doc1">Doctor 1</option>
<option value="doc2">Doctor 2</option>
<option value="doc3">Doctor 3</option>
<option value="doc4">Doctor 4</option>
</select>
<input type="submit">
</form>
</body>
</html>
In your php file you should check for $_POST['doctor']
after you check if form is submitted. Then like @Kern pointed set $_SESSION['selected']
with appropriate variable.
For easier debugging use var_dump($variable) which will help you most of the times to find trivial errors. So var_dump($_POST) at the beginning of the script to find out what happening.