3

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.

3
  • 3
    LIKE %elementary% => LIKE '%elementary%' and do the same for the others. You're not checking for DB errors. If that still doesn't work, then it's also a scope issue. Commented Oct 16, 2014 at 14:28
  • You can get the exact error from mysqli by using mysqli_error or you can have mysqli throw exceptions. Commented Oct 16, 2014 at 14:30
  • You're trying to parse strings not integers you should get an error. Please try '%all%' instead of %all% Commented Oct 16, 2014 at 14:34

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.