I built a form that can select data from MySQL database and the desired field of the selected row will be displayed in an input field of a form. However, this form is dynamic in the sense that you can have multiple forms of the same form.
If two or more forms are generated, only the first form is auto populated. I want each form to auto-populate their corresponding input field upon selection of a row from the database.
Here is the code:
<?php
$start=1;
$end= $_POST['item']; echo'<br>';
for($start;$start<=$end;$start++){
require("connect.php");
$sql = "(SELECT * FROM drug_name)";
$result = mysqli_query($conn, $sql);
?>
<form align="center" method="post" action="transaction.php">
Name:
<select align="right" name="inputname[]" onchange="showunit(this.value); showqty(this.value)"
value="inputvalue[]">
<option selected="selected" value="0">S/N Select drug --</option>
<?php while($row = $result->fetch_assoc()){ ?>
<option value='<?php echo $row['SN']; ?>'><?php
echo$row['Drug_Item_Name']?></option>
<?php
}
?>
</select>
<td align="right">Stock Level:</td>
<td><input type="text" name="input3[]" placeholder="Enter QTY" size="5" id="displayqty"></td>
</tr>
<?php echo '<br>'; ?>
<?php }
?> </form>
This is the code to make the AJAX code:
<script>
function showqty(str) {
if (str == "") {
document.getElementById("displayqty").value = "";
return; `
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("displayqty").value = xmlhttp.responseText;
}
}
xmlhttp.open("GET","qtydisplay.php?q2="+str,true);
xmlhttp.send();
}
}
</script>
This is the AJAX code to fetch data from MySQL database:
<?php
$q2 = intval($_GET['q2']);
include("connect.php");//connection to database
mysqli_select_db($conn,"ajax_demo");
$sql="SELECT Qty_Stocked FROM drug_name WHERE SN = '".$q2."' LIMIT 1";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array( $result)) {
echo $row['Qty_Stocked'];
}
mysqli_close($conn);
?>