Reputation: 135
I am trying to search my SQL database with a simple search form and then return the data to the screen.
For example, the user can select a year, then all the row results from the table display all of the information for that entry. Here is my form:
<form class="" method="POST" action="availability.php" enctype="multipart/form-data">
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<input class="btn btn-blue-grey" type="submit" value="submit">Search
<i class="fas fa-search ml-1"></i>
</input>
</form>
And here is my PHP
if(isset($_POST['submit'])) {
$year = $_POST['year'];
var_dump($year);
var_dump($_POST);
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll(); }
and my HTML
<ul>
<?php foreach($data as $stmt) { ?>
<li><?php echo $stmt['cruise'];?></li>
<li><?php echo $stmt['year'];?></li>
<?php } ?>
</ul>
At the minute, the form submits, but I get nothing populating the list.. Any help would be appreciated.
Upvotes: 0
Views: 1079
Reputation: 913
You can try to use this query :
$year = $_POST['year'];
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll();
Upvotes: 2
Reputation: 135
you must change a few thing, first, edit the select tag to:
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
There is a condition that seems it is wrong. so, change your html code to
if($_POST) {
$year = $_POST['year'];
$stmt = $pdo->prepare("SELECT * FROM availability WHERE year = :year");
$stmt->execute(array("%$year%"));
// fetching rows into array
$data = $stmt->fetchAll();}
Upvotes: 0
Reputation: 897
$stmt->bindParam(':year',$year,PDO::PARAM_STR); <-- does this need to be PARAM_INT ?
also have you var_dump'ed $year = $_POST['year']; to make sure you are getting a value?
You could turn on error_reporting and see if you get any useful errors
Upvotes: 0