I have a HTML form which has 3 text input fields: id, name, and contact. My DB table has same named columns and the values are id=1, name=mark & contact=1234. Now, if I enter ‘1’ in my html form’s id field & press enter then how can the rest of the form’s field (like: name, contact) will be automatically filled?
What I’ve done so far is:
my index.html file(I think its wrong because I didn’t use JSON before):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type = javascript>
$("#email").bind("change", function(e){
$.getJSON("lookup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
</script>>
</head>
<body>
<form>
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
</form>
</body>
</html>
my lookup.php file:
<?php
//look up the record based on email and get the firstname and lastname
$email=$_GET['$email'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("json", $con); //DB name= json
mysql_select_db("json"); //DB name= json
$result = mysql_query("SELECT * FROM json1
WHERE email LIKE '$email%'"); //DB table name=json1
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
}
}
?>
To fill the form without reloading the page you will have to use Ajax to request the data from the server (database) and then fill it using javascript, i suggest reading about ajax functions with jquery.
if you want for example to fill the id and click a button and the page will reload with the data, use the php post method, a quick example:
UPDATE:
regarding your update
first of all you better use PDO or MySQLi database instead of MySQL function because mysql_* is no longer maintained so since you are fresh to php learn PDO instead.
to your code, if you are expecting a single row from the database select statement, you should not use
while()because its used to loop through the mysql object which has more than one row.if we assume your table has exactly
email, firstname, lastnamefetch it directly into an array:then convert that array into json and print it out