Search code examples
phpmysqliget

How do I check 1st $_GET for a value and print or check 2nd and print if value is different?


To clarify title, here's my code. It's not working--I'm sure it's wrong. But I don't know if I'm close or far away from the answer. I have an "Any" option that I want to reveal everything in my database as opposed to the selected option which would only reveal specific rows. I'm not sure how to display the former. Thanks!

   $Interest = $_GET['interestId'];



 $sql = "SELECT * from User WHERE (Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest' OR $Interest = 'Any Interest');";

   $result = mysqli_query($link, $sql);

   $resultCheck = mysqli_num_rows($result);

    if ($resultCheck > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo "<p>";
            echo Name . ": ";
            echo $row['Fname'] . " ";
            echo $row['Lname'] . "<br><br>";
            echo Interests . ": ";
            echo $row['Interest1'] . ", ";
            echo $row['Interest2'] . ", ";
            echo $row['Interest3']  . "<br><br>";
            echo Website . ": ";
            echo $row['Website']  . "<br><br>";
            echo Personal_Statement . ": <br><br>";
            echo $row['PersonalStatement'] . "<br><br>";
            echo Contact . ": ";
            echo $row['Phone']  . "<br>";
            echo $row['Email'];
            echo "</p>";
        }
    } else {
        echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
    }

Now it doesn't return anything for any selection.


Solution

  • So if $Interest is "Any" then there should be no filter at all? You can put that logic in the query. For example, consider something like this:

    SELECT *
    FROM User
    WHERE
      (Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest')
      OR '$Interest' = 'Any'
    

    Under this logic that last OR will match every record if the variable has the string "Any". So you're basically saying "if the record matches the input, OR if the input is Any".

    Also, and this is important, your code is wide open to SQL injection. What that means is that you blindly execute any code your users send you. This answer demonstrates the logic of a solution, but there is more you need to do. Start by learning what SQL injection is here, and some quick information about how to meaningfully prevent it here.