user3806613
user3806613

Reputation: 510

echo select options in php page?

I'm trying to echo the select options using mysql results.

my code bellow only gets one result but I have 5 results in mysql database!

PHP CODE:

if( ! $stmt = $db_conx->prepare("SELECT id, product_name FROM $storeShop ORDER by id") ) {
  die( $db_conx->error );
}
$dropdownlist_list = "";
$stmt->bind_param('i', $id);
if ( ! $stmt->execute() ) {
  die( $stmt->error );
}
$stmt->bind_result($id, $product_name);
$stmt->store_result();

while($stmt->fetch()) {
    $valuesss[] = array('id'=>$id, 'product_name'=>$product_name);
$dropdownlist_list = '<option data-filter="'.$product_name.'">'.$product_name.'</option>';
    }

    /* close statement */
    mysqli_stmt_close($stmt);

HTML CODE:

<select id="galleryfilter" class="form-control pull-left">
                                       <?php echo $dropdownlist_list; ?>

</select>

Could someone please tell me whats wrong?

Thanks

Upvotes: 0

Views: 597

Answers (4)

Raphael M&#252;ller
Raphael M&#252;ller

Reputation: 2200

you have to use $dropdown_list .= instead of = this will append the new options.

this results in:

$dropdown_list = "";
while($stmt->fetch()) {
    $valuesss[] = array('id'=>$id, 'product_name'=>$product_name);
    $dropdown_list .= '<option data-filter="'.$product_name.'">'.$product_name.'</option>';
}

Upvotes: 1

Andr&#233;
Andr&#233;

Reputation: 477

Your current solution overwrites the existing string each time a new statement is loaded.

Try this:

$dropdownlist_list = "";
while($stmt->fetch()) {
    $valuesss[] = array('id'=>$id, 'product_name'=>$product_name);
    $dropdownlist_list .= '<option data-filter="'.$product_name.'">'.$product_name.'</option>';
}

Or a nicer solution:

while($stmt->fetch()) {
    $values[] = array('id'=>$id, 'product_name'=>$product_name);
}

HTML:

<select id="galleryfilter" class="form-control pull-left">
<?php 
    foreach ($values as $value) echo '<option data-filter="'.$value['product_name'].'">'.$value['product_name'].'</option>';
?>
</select>

Upvotes: 2

DarkBee
DarkBee

Reputation: 15625

$dropdownlist_list  '';    
while($stmt->fetch()) {
    $valuesss[] = array('id'=>$id, 'product_name'=>$product_name);
    $dropdownlist_list .= '<option data-filter="'.$product_name.'">'.$product_name.'</option>';
}

U are overwiting your options string each time. U need to append the other options

Upvotes: 1

George Sharvadze
George Sharvadze

Reputation: 570

You have to append new options, currently you are assigning the last value from the database

This will work: $dropdownlist_list .= '<option data-filter="'.$product_name.'">'.$product_name.'</option>';

Upvotes: 2

Related Questions