0

I have a multiple select form like so:

<form name="form" action="result2.php" method="post">
    <label>Type of Resource</label>
        <select name="resources[]" multiple>
            <option>Charitable Organization</option>
            <option>Women-Only Shelter</option>
            <option>Men-Only Shelter</option>
            <option>Family Shelter</option>
            <option>Youth Shelter</option>
            <option>Emergency Shelter</option>
        </select>  
       <input type="submit" value="Submit">
</form>

The user will be able to select multiple options and all the shelter in my database under each selected categories will be displayed. Here is my php code:

$value_4 = $_POST["resources"];

if($value_4){
foreach ($value_4 as $v){
    $result = mysqli_query($dbc, "SELECT DISTINCT shelter_name, type_name
    FROM shelter s 
    INNER JOIN shelter_type st on s.shelter_id = st.shelter_id
    INNER JOIN s_type stt on st.type_id = stt.type_id
    WHERE type_name = '$v'");
}
}

echo"<table border='1'>";
echo"<tr><td>Shelter</td><td>Type</td></tr>";

while ($row = mysqli_fetch_assoc($result)){
    echo"<tr><td>{$row['shelter_name']}</td><td>{$row['type_name']}</td></tr>";}

echo"</table>";

Currently, I can only get the LAST selected option to display. How can I change my php code that ALL the data under each selected option get displayed? Thanks.

Fran
  • 98
  • 1
  • 12
  • You're overwriting `$result` on each loop iteration, so by the time you exit the loop, it contains only the query results from the last iteration. – Alex Howansky Apr 04 '18 at 14:41
  • Also, your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Apr 04 '18 at 14:41
  • 1
    You might be also able to change that loop to a single query with something like `WHERE type_name IN ()`. – Alex Howansky Apr 04 '18 at 14:43
  • @AlexHowansky You're right, I was overwriting $result. I put the echo table part inside my foreach loop and it works. I'll look up the points you've mentioned as well. Thank you!! – Fran Apr 04 '18 at 14:52

1 Answers1

0

Like @Alex Howansky mentioned, I was overwriting my $result on each loop iteration. I simply moved the second part of my code that prints out the shelter inside my foreach loop and it works!

Fran
  • 98
  • 1
  • 12