user2710234
user2710234

Reputation: 3225

fill other text inputs with MySQL values based on select box option

I have this select box that populates from MySQL Data using PHP

<select>
    <?php
    $stmt = $pdo_conn->prepare("SELECT * from prices ");
    $stmt->execute(array());
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($records as $result2) {
        echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
    }
    ?>
    </select>

in the same table in MySQL (prices) there is a retail column, how can i put the value of retail into a text input

<input type="text" name="unitprice" />

based on the selected row in the select box?

Upvotes: 0

Views: 3051

Answers (1)

Death By Penguin
Death By Penguin

Reputation: 111

I'd recommend using JavaScript.

Option 1

I would convert your results into a JSON Array and echo it to JavaScript. This way all information gets given the user.

<select id="mySelectBox" onchange="changeValue(this.value);">
<?php
$json_array = array();
$stmt = $pdo_conn->prepare("SELECT * from prices ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result2) {
    $product = $result2["product"];
    $json_array[$product] = $result2['unitprice'];
    echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
}
json_encode($json_array, JSON_FORCE_OBJECT);
?>
</select>
<input type="text" id="unitPrice" name="unitprice" />


<script>
var json = <?php echo $json_array; ?>;
function changeValue(myValue) {
    document.getElementById("unitPrice").value = json[myValue];
}


</script>

Upvotes: 2

Related Questions