Php: change value of variable based on dropdown

Learning PHP and a problem I can't figure out. I read that PHP only has capabilities for functions, so I'm not sure why my switch statement is not changing the value of the variables.

Purpose: Modify mysql SELECT statement based on user selection of dropdown.

the 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 the 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);

      

confirm_query function if needed:

    function confirm_query($result_set) {
    if (!$result_set) {
        die("Database query failed.");
    }
}

      

When All Levels is selected from the dropdown list, the code works as expected. When any other option is selected, my confirm_quaery function states that the request is failing.

I'm not sure why the variable values ​​are not toggling.

+3


source to share


1 answer


To comment on my comment:

Change LIKE %elementary%

to => LIKE '%elementary%'

and do the same for the rest.

You need to wrap the pattern match in quotes and according to the guide:



mysql> SELECT 'David!' LIKE '% D% v%';
mysql> SELECT 10 LIKE '1%';

You also don't check for DB errors.

Add or die(mysqli_error($connection))

tomysqli_query()

If that still doesn't work, then it is also a scope issue.
Pass the connection to your function, make it not global.

+2


source







All Articles