Learning PHP and having an issue that I can’t figure out. I have read that PHP only has scope for functions, so I’m not sure why my switch statement isn’t changing the value of variables.
Goal: to change the mysql SELECT statement based on user selection of drop-down.
Form:
<form action="contacts_show.php" method="POST">
<select name="grade" id="grade">
<option value="all">All Levels</option>
<option value="elementary">Elementary</option>
<option value="middle">Middle</option>
<option value="senior">Senior</option>
<input type="submit" name="browse" id="browse" value="Browse" />
</form>
PHP (edited to shorten code):
$levelSelected = $_POST['grade'];
if ($levelSelected == "all") {
$querySelect = "SELECT * FROM teachers ORDER BY school ASC";
} else {
$querySelect = "SELECT * FROM teachers WHERE school LIKE %$levelSelected% ORDER BY school ASC";
}
$query = $querySelect;
$result = mysqli_query($connection, $query);
confirm_query($result);
the confirm_query function, if needed:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
When “All Levels” from drop-down is selected, code runs as expected. When any other option is selected, my confirm_query function states that the query fails.
I’m not sure why the variable’s values are not switching.
Advertisement
Answer
To elaborate on my comment:
Change LIKE %elementary%
to => LIKE '%elementary%'
and do the same for the others.
You need to wrap the pattern match in quotes, and as per the manual:
mysql> SELECT ‘David!’ LIKE ‘%D%v%’;
mysql> SELECT 10 LIKE ‘1%’;
You’re also not checking for DB errors.
Add or die(mysqli_error($connection))
to mysqli_query()
If that still doesn’t work, then it’s also a scope issue.
Pass the connection to your function, do not make it global.