I'm trying to store the name of the select option instead of the value in the MySQL database. The current code is storing customer id instead of customer name in the database. I know some of you will say that why don't you use $customer_result['name'] in the name attribute but If I did this, then I wouldn't be able to filter the record using id
MYSQL and PHP
<?php
$select_customer = "select * from customer";
$select_customer_query = mysqli_query($connection, $select_customer); // Customer Data
if(isset($_POST['add-sale-btn'])) {
$customer_name = mysqli_real_escape_string($connection, $_POST['customer_name']);
$customer_address = mysqli_real_escape_string($connection, $_POST['customer_address']);
$insert_sale = "insert into sale(customer_name, customer_address) values('$customer_name','$customer_address')";
$insert_sale_query = mysqli_query($connection, $insert_sale);
}
?>
<form method="post" action="">
<div class="form-group">
<select class="form-control" id="customer_name" name="customer_name">
<option>Customer Name</option>
<?php while($customer_result = mysqli_fetch_assoc($select_customer_query)) { ?>
<option value="<?php echo $customer_result['id']; ?>"><?php echo $customer_result['name']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group" style="margin-top:10px;">
<input type="submit" class="btn btn-primary" name="add-sale-btn" value="Save">
</div>
</form>
JQuery Code
<script>
$(document).ready(function(){
$('#customer_name').on('change', function(){
var customer_name = $('#customer_name').val();
$.ajax({
url: 'customer-detail.php',
type: 'POST',
data: {id : customer_name},
success: function(customer_data){
$('#customer_detail').html(customer_data);
}
});
});
});
</script>
customer-detail.php
$select_customer_detail = "select * from customer where id={$_POST['id']}";
$customer_detail_query = mysqli_query($connection, $select_customer_detail);
$customer_detail_result = mysqli_fetch_assoc($customer_detail_query);
<div class="form-group">
<input type="text" class="form-control" name="customer_address" value="<?php echo $customer_detail_result['address']; ?>">
</div>