Search code examples
phprankingretain

Retaining ranked values selected from a dropdown box


I am ranking the values of the products and listing them in a drop down menu. I can't seem to retain the selected ranked value from the drop down menu. Any help would be appreciated, thanks in advance.

<?php

$sessionid = $_SESSION['uid'];

$period = ".&nbsp";

$info = $conn->prepare("SELECT `productid`,`name` FROM `products` WHERE id = :id  ORDER     BY `name` DESC ");
$info ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info->execute();

$rank = 0;
$last_score = false;
$rows = 0;

$ops = '';  

while ($userinfo = $info->fetchobject()) {


$rows++;
if( $last_score!= $userinfo->name ){
$last_score = $userinfo->name;
$rank++;
}

$productid1 = "$userinfo->productid";
$name1 = "$userinfo->name";
$ops.= "<option value='" . $productid1 . "'>" . $rank . "" . $period . "" . $name1 .   "</option>";

}          
?>

<form action="store.php" method="POST">

<b>Select a product from our top ranking product list. </b> </br>
<select name= "products" >

<?php echo $ops ?> <?php if($_POST['products']=='$ops') echo "selected =  \"selected\""; ?>>
</select>
</br>
<input type="submit" name="Submit" value="Submit"/>
</form>

Solution

  • This won't work where you have it:

    if($_POST['products']=='$ops') echo "selected =  \"selected\"";
    

    You need to do that here:

    $ops .= "<option value='" . $productid1 . "'";
    if($_POST['products']==$productid1) {$ops .= "selected =  'selected'";}
    $ops .= ">" . $rank . "" . $period . "" . $name1 .   "</option>";