I have an html page that loads list of hotels in a select
tag from a MySQL table using PHP. The select
tag is inside a form
tag. Whenever I load the page, the option
tags will load, but when I submit my form
, the option
tags never load anymore. My form
's action
attribute is empty, I am checking everything on the same page, but when I put another php page as action
, it loads normally. Is there a way to make it load after submit while keeping my form
's action
empty?
Here is my code
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
$db->disconnect();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
If $_POST['search']
is set, you $db->disconnect();
so it can't run the query in your form.
Take the $db->disconnect();
out of your if()
statement, and put it at the end of the file.
The issue is with the disconnect, when the page reload after submit your connection to mysql lost due to
$db->disconnect();
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>