Fetch Value From Database And Fill All Textbox If Dropdown Value Change June 11, 2024 Post a Comment I am trying to fill all textbox value depend on dropdown value selection. And I also fill dropdown value by SQL query. Here is HTML Code: CopyAnd change the following statement echo"<option value='$r[0]'> $r[0] </option>"; CopyToecho'<option data-add="'.$r[1].'" data-con="'.$r[2].'" value='.$r[0].'> '.$r[0].' </option>'; CopyModify select as<select name="name" ID="name"class="form-control" onchange="myFunction()"> CopyAdd the following javascriptfunctionmyFunction(){ var index = document.getElementById("name").selectedIndex; var add = document.getElementById("name").options[index].getAttribute("data-add"); var con = document.getElementById("con").options[index].getAttribute("data-con"); document.getElementsByName("add")[0].value = add; document.getElementsByName("con")[0].value = con; } CopyJsFiddle CodeSolution 2: A bit of description: The first time when you are accessing the page (index.php) the data is loaded into the combobox. Each option tag receives the client number as value (C_no) and other details, as text.On the other hand, when you are selecting a value in the combobox, you need to fetch additional client data from the database. For this you need jquery and ajax. With it, when the value of the combobox changes, you must make an ajax request to the server (getClient.php). As response it sends you the corresponding data from the database table. You then take the data and put it wherever you like - in this case in the inputs.A bit of suggestion: I would recommend you to start using prepared statements - in order to avoid sql injection - and to not mix php code for fetching data from db with html code. Just separate them. First, fetch data on top of the page and save it into an array. Then, inside the html code, use only the array to iterate through fetched data.index.php<?phprequire'connection.php'; $sql = 'SELECT C_no, Cname, Caddress FROM Client_table ORDER BY Cname ASC'; // Prepare the statement.$statement = mysqli_prepare($connection, $sql); // Execute the statement. mysqli_stmt_execute($statement); // Get the result set from the prepared statement.$result = mysqli_stmt_get_result($statement); // Fetch the data and save it into an array for later use.$clients = mysqli_fetch_all($result, MYSQLI_ASSOC); // Free the memory associated with the result. mysqli_free_result($result); // Close the prepared statement. It also deallocates the statement handle. mysqli_stmt_close($statement); ?><!DOCTYPE html><html><head><metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1" /><metaname="viewport"content="width=device-width, initial-scale=1, user-scalable=yes" /><metacharset="UTF-8" /><!-- The above 3 meta tags must come first in the head --><title>Demo</title><scriptsrc="https://code.jquery.com/jquery-3.2.1.min.js"type="text/javascript"></script><scripttype="text/javascript"> $(document).ready(function () { $('#name').change(function (event) { var cNo = $(this).val(); if (cNo === 'Select') { $('#address').val(''); $('#contact').val(''); } else { $.ajax({ method: 'post', dataType: 'json', url: 'getClient.php', data: { 'cNo': cNo }, success: function (response, textStatus, jqXHR) { if (!response) { alert('No client data found.'); } else { $('#address').val(response.address); $('#contact').val(response.contact); } }, error: function (jqXHR, textStatus, errorThrown) { alert('An error occurred. Please try again.'); }, cmplete: function (jqXHR, textStatus) { //... } }); } }); }); </script><styletype="text/css">body { padding: 30px; } input, select { display: block; margin-bottom: 10px; } </style></head><body><divclass="container"><selectname="name"id="name"class="form-control"><optionvalue="Select">- Select -</option><?phpforeach ($clientsas$client) { ?><optionvalue="<?phpecho$client['C_no']; ?>"><?phpecho$client['Cname'] . ' (' . $client['Caddress'] . ')'; ?></option><?php } ?></select><label>Address</label><inputtype="text"id="address"name="address"/><label>Contact</label><inputtype="text"id="contact"name="contact"/></div></body></html>CopygetClient.php<?phprequire'connection.php'; // Validate posted value.if (!isset($_POST['cNo']) || empty($_POST['cNo'])) { echo json_encode(FALSE); exit(); } $cNo = $_POST['cNo']; $sql = 'SELECT Caddress AS address, Ccontact AS contact FROM Client_table WHERE C_no = ? LIMIT 1'; // Prepare the statement.$statement = mysqli_prepare($connection, $sql); /* * Bind variables for the parameter markers (?) in the * SQL statement that was passed to prepare(). The first * argument of bind_param() is a string that contains one * or more characters which specify the types for the * corresponding bind variables. * * @link http://php.net/manual/en/mysqli-stmt.bind-param.php */ mysqli_stmt_bind_param($statement, 'i', $cNo); // Execute the statement. mysqli_stmt_execute($statement); // Get the result set from the prepared statement.$result = mysqli_stmt_get_result($statement); // Fetch the data and save it into an array for later use.$clientDetails = mysqli_fetch_array($result, MYSQLI_ASSOC); // Free the memory associated with the result. mysqli_free_result($result); // Close the prepared statement. It also deallocates the statement handle. mysqli_stmt_close($statement); if (!isset($clientDetails) || !$clientDetails) { echo json_encode(FALSE); } else { echo json_encode($clientDetails); } exit(); Copyconnection.php<?php// Db configs. define('HOST', 'localhost'); define('PORT', 3306); define('DATABASE', 'your-db'); define('USERNAME', 'your-user'); define('PASSWORD', 'your-pass'); // Display eventual errors. error_reporting(E_ALL); ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */// Enable internal report functions.$mysqliDriver = new mysqli_driver(); $mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Create db connection.$connection = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT); CopyCreate table syntaxDROPTABLE IF EXISTS `Client_table`; CREATETABLE `Client_table` ( `C_no` int(11) unsigned NOTNULL AUTO_INCREMENT, `Cname` varchar(100) DEFAULTNULL, `Caddress` varchar(100) DEFAULTNULL, `Ccontact` varchar(100) DEFAULTNULL, PRIMARY KEY (`C_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERTINTO `Client_table` (`C_no`, `Cname`, `Caddress`, `Ccontact`) VALUES (1,'Mohit','xyz','0123645789'), (2,'Ramesh','abc','7485962110'), (5,'Tanja','def','1232347589'), (6,'Paul','pqr','0797565454'), (7,'Mohit','klm','0123645789'); CopySolution 3: <?php$servername = "localhost"; $username = "root"; $password = ""; $dbname="stack"; // Create connection mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $conn = new mysqli($servername, $username, $password, $dbname); $qu = "SELECT DISTINCT Cname,Caddress,Ccontact FROM Client_table"; $res = $conn->query($qu); ?><selectname="name"ID="name"onchange="myFunction()"class="form-control"><optionvalue="Select">Select</option><?phpwhile($r = mysqli_fetch_row($res)) { echo"<option data-add='$r[1]' data-con='$r[2]' value='$r[0]'> $r[0] </option>"; } ?></select><label>Address</label><inputtype="text"name="add"id="add"/><label>Contact</label><inputtype="text"name="con"id="con"/><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>functionmyFunction(){ var address = $('#name').find(':selected').data('add'); var contact = $('#name').find(':selected').data('con'); $('#add').val(address); $('#con').val(contact); } </script>CopySolution 4: JavaScript File: functiongetdata(str) { if (str == "") { document.getElementById("no_of_sms").value = ""; document.getElementById("no_of_days").value = ""; document.getElementById("descr").value = ""; document.getElementById("state-pkg").value = ""; document.getElementById("price-pkg").value = ""; return; } if (window.XMLHttpRequest) { xmlhttp = newXMLHttpRequest(); } else { xmlhttp = newActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (this.readyState==4 && this.status==200) { var data = xmlhttp.responseText.split("#"); var db_no_of_sms = decodeURIComponent(data[0]); var db_no_of_days = decodeURIComponent(data[1]); var db_f_state = decodeURIComponent(data[2]); var db_f_price = decodeURIComponent(data[3]); var db_f_desc = decodeURIComponent(data[4]); document.getElementById("no_of_sms").value=db_no_of_sms; document.getElementById("no_of_days").value = db_no_of_days; document.getElementById("descr").value = db_f_desc; document.getElementById("state-pkg").value = db_f_state; document.getElementById("price-pkg").value = db_f_price; } } xmlhttp.open("GET","functions/getdata.php?q="+str,true); xmlhttp.send(); } CopyPHP File : <?php$q = $_GET['q']; $host="localhost"; $db_username="root"; $db_password=""; $con = mysqli_connect("$host", "$db_username", "$db_password"); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"business_details"); $sql="SELECT * FROM packages where p_name = '$q'"; $result = mysqli_query($con,$sql); $row=mysqli_fetch_assoc($result); $db_no_of_sms = $row['no_of_sms']; $db_no_of_days = $row['days']; $db_f_state = $row['state']; $db_f_price = $row['price']; $db_f_desc = $row['description']; echo$db_no_of_sms."#".$db_no_of_days."#".$db_f_state."#".$db_f_price."#".$db_f_desc; ?>CopySolution 5: type: "GET", dataType: "json", success: function(data) { console.log(data[0]['qty']); $.each(data, function(key, value) { $('#qty').val(data[0]['qty']); }); } }); Copy Share Post a Comment for "Fetch Value From Database And Fill All Textbox If Dropdown Value Change" Top Question Creating Popup Window With Form Content And Then Show Output In Parent Page And Send To Database I have a table and in of it's column I want user when c… Get The Value Of Checked Radio Button Without Re-selecting The Buttons So I am getting some buttons as follows: var reportFilterBu… JQuery Val Is Undefined? I have this code: But when i write $('#editorT Sol… Onsubmit Method Doesn't Stop Submit My onsubmit is not working. My idea was to put some mandato… "too Much Recursion" Error When Calling JSON.stringify On A Large Object With Circular Dependencies I have an object that contains circular references, and I w… Configuring Any Cdn To Deliver Only One File No Matter What Url Has Been Requested I am currently working on a new project where the entire pa… Display Modal Form Before User Leaves Page I've used window.onbeforeunload to display a custom mes… How To To Insert TradingView Widget Into React Js Which Is In Script Tag Link: Https://www.tradingview.com/widget/market-overview/ export default class extends Component { render() { … React Mobx - Store Return Proxy Object I have the following state class: import { observable, acti… Angular : Can't Export Excel Using Exceljs - Error Ts2307: Cannot Find Module 'stream' - Error Ts2503: Cannot Find Namespace 'nodejs' I was try to export an excel file using ExcelJS Here is my … December 2024 (1) November 2024 (39) October 2024 (73) September 2024 (25) August 2024 (378) July 2024 (341) June 2024 (721) May 2024 (1296) April 2024 (820) March 2024 (1581) February 2024 (1732) January 2024 (1395) December 2023 (1450) November 2023 (435) October 2023 (620) September 2023 (278) August 2023 (336) July 2023 (264) June 2023 (355) May 2023 (201) April 2023 (121) March 2023 (153) February 2023 (182) January 2023 (245) December 2022 (126) November 2022 (241) October 2022 (177) September 2022 (165) August 2022 (482) July 2022 (287) June 2022 (249) Menu Halaman Statis Beranda © 2022 - JavaScript Download