Looping through results in mysqli

2019-04-21 06:03发布

问题:

I am new to mysqli and having a problem looping through results with mysqli. Unfortunately, I am only getting a single result. When I put the query into phpMyAdmin, it comes up with three results. I believe the relevant code is here and that I am just calling it wrong:

$connection = new mysqli($host, $databaseUsername, $databasePassword, $database);

if ($connection->connect_errno > 0) {
    die ('Unable to connect to database [' . $connection->connect_error . ']');
}

$sql = "SELECT clientId, studentFirstName, studentLastName
        FROM clients
        WHERE (studentEmail = '$postEmail') OR (parentEmail = '$postEmail');";  

if (!$result = $connection->query($sql)) {
    die ('There was an error running query[' . $connection->error . ']');
}

echo '<select class = "toolbarDropdown" id = "toolbarDropdown-MultipleAccounts">';

    while ($row = $result->fetch_array()) {
        echo '<option value="'.$row["clientId"].'">'.$row["studentFirstName"].' '.$row["studentLastName"].'</option>';
    }

echo '</select>';

回答1:

You are missing the closing " at option="value <-- in your HTML

Note that

$row = $result->fetch_array()

can be replaced by

$row = $result->fetch_assoc()

Doing so, the array for each record you fetch would take half of the size.