简体   繁体   中英

PHP - Auto-fill text-boxes based upon drop-down value selected?

Morning all,

I'm building a web app in HTML/ PHP and have an edit product page which has a select drop-down which is populated from the products stored in a MySQL database. Image of the form below;

编辑产品表格

The corresponding data for each field is stored also in the database, I can not work out for the life of me how I get the textboxes to feature the corresponding information when the product is selected via the dropdown, and I am struggling to find any tutorials on how I can get this too work? I understand that I may need to use AJAX to fetch the informaiton without reloading the page. Apologies for noob quesitons I'm new too this,

As always, any help appriciated,

Thanks.

PHP So far which populates the select dropdown:

<?php
    or die ('Cannot connect to db');

    $result = $conn->query("select ID, NAME from PRODUCTS");
    print "<h3>EDIT PRODUCT</h3>"; 
    print "<p>&nbsp;<strong>SELECT PRODUCT: <br><br></strong>" . "<select name='ID'";

    while ($row = $result->fetch_assoc()) {
        unset($id, $name);
        $id = $row['ID'];
        $name = $row['NAME']; 
        echo '<option value="'.$id.'">'.$name.'</option>';
    }
?>

You need to use some javascript! Take a look at the following... I haven't tested this so you may get an error but it should be simple to fix.

I only added some code to pre-fill a single text box after selecting a product in the select box but you should be able to figure out the rest.

<?php

$conn = new mysqli('localhost', 'bradleyb_badbrad', '20password40', 'bradleyb_testDb')
or die ('Cannot connect to db');

$result = $conn->query("select ID, NAME from PRODUCTS");

// Build up an array of options to show in our select box.
$productSelectOptions = array();
while ($row = $result->fetch_assoc()) {
    $productSelectOptions[$row['ID']] = $row['NAME'];
}

?>

<h3>EDIT PRODUCT</h3>

<p>
    <strong>SELECT PRODUCT:</strong>
    <select name="ID" id="productSelect">
        <?php foreach ($productSelectOptions as $val => $text): ?>
            <option value="<?= $val; ?>"><?= $text; ?></option>
        <?php endforeach; ?>
    </select>
</p>

<h3>ID:</h3>

<p>
    <input type="text" name="id_text" id="idText" />
</p>

<!-- Include jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script>
    var $productSelect = $('#productSelect');
    var $idText = $('#idText');

    // This should be the path to a PHP script set up to receive $_POST['product']
    // and return the product info in a JSON encoded array.
    // You should also set the Content-Type of the response to application/json so as our javascript parses it automatically.
    var apiUrl = '/getProductInfo.php';

    function refreshInputsForProduct(product)
    {
        $.post(apiUrl, {product: product}, function(r) {
            /**
             * Assuming your PHP API responds with a JSON encoded array, with the ID available.
             */
            $idText.val(r.ID);
        });
    }

    // Listen for when a new product is selected.
    $productSelect.change(function() {
        var product = $(this).val();
        refreshInputsForProduct(product);
    });
</script>

An example PHP API with some general instructions... /getProductInfo.php

<?php
header('Content-Type: application/json');
$response = array(
    'ID' => null,
);

if (array_key_exists('product', $_POST)) {
    $product = $_POST['product'];

    // Now we fetch the product info from the database.
    // SELECT ID FROM product_info WHERE product = $product
    // Imagine the result is stored in $result
    $result = null;

    $response['ID'] = $result['ID'];
}

echo json_encode($response);

I wasn't meaning to give you fully working code that immediately fixes your issue, but was more looking to show you the general way to go about these things.

I hope this helps!

Try the following -

<p>
    <label for="inputState">State:</label>
    <select type="text" class="form-control show-tick" name="state" id="state" value="<?php echo $row['state']; ?>">
        <option value="0">Select State</option>
        <?php
            $sql = "SELECT * FROM states ";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $name =  $row['name'];
                    $id =  $row['id'];
                    echo "<option value='$id'".(($state == $id)? 'selected' : '').">$name</option>";
                }
            } 
        ?>
    </select>
    <span class="error"><?php echo $stateErr; ?></span>
</p>

There is two way to solve this problem via AJAX or via submitting form. Example via php form submit.

<?php 
 //after submitting the form you get the value of selected product
if(isset($_GET['id'])){
   $product_id=$_GET['ID'];
   $productQuery = $conn->query("select ID, NAME from PRODUCTS WHERE ID='".$."'");
  $productResult = $productQuery ->fetch_assoc()
  //use the value of productResult in your textbooxes
}else{ 
   $productResult =array();
}
<form method='get' action=''>
  <select name='ID' onchange="this.form.submit()">
 <?php
     while ($row = $result->fetch_assoc()) {
        unset($id, $name);
        $id = $row['ID'];
        $name = $row['NAME']; 
        echo '<option value="'.$id.'">'.$name.'</option>';
  }?>
 </select>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM