a2b2c2
a2b2c2

Reputation: 15

PHP <select> is not populating results

I am trying to write a php to fetch from a mysql dba and use the result set in a dropdown list as a input for another php to query on the variable. Ideally I only want to show the lastname, firstname, and Call Sign while using the MembersId as the argument for the form php.

I get a drop down list to show but it has no data. When I look at the source I see that the query ran and can see the result set.

I appreciate any advice I can get.

<html>

<?php

include('connectDb.php');

$sql="Select MembersId, lastName, firstName, callSign from 
SVARC.members";

$stmt = $pdo->prepare($sql);

$stmt->execute();

$users = $stmt->fetchAll();

?>

<form action="LastMeetingAttendancebyDate.php" method="post">
<select name ="user">

    <?php
        foreach($users as $user){
            echo("<option value='");
            echo($user['MembersId']+"'>");
            echo($user['lastName']);
            echo",";
            echo($user['firstName']);
            echo" ";
            echo($user['callSign']);
            echo("'</option>");
        }
    ?>
 </select>
 <input type="submit">
</form>

Upvotes: 0

Views: 35

Answers (1)

Jeto
Jeto

Reputation: 14927

On this line:

echo($user['MembersId']+"'>");

you're attempting to concatenate using +. The concatenation operator in PHP is ..

However, I would suggest rewriting your block of code like this:

<select name="user">
    <?php foreach ($users as $user): ?> 
    <option value="<?= $user['MembersId'] ?>">
        <?= $user['lastName'] ?>, <?= $user['firstName'] ?> <?= $user['callSign'] ?>
    </option>
    <?php endforeach ?>
</select>

This makes use of PHP's alternative syntax for control structures which is particularly nice for outputting things like HTML.

I would also recommend using htmlspecialchars on the values to avoid potential XSS attacks. Didn't add them to the sample to keep it simple, but you should look into it at the very least.

Upvotes: 2

Related Questions