473,767 Members | 2,198 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP autofill text box from MySQL

9 New Member
I realize this should probably be a simple solution, but I have only been learning PHP and MySQL for a couple weeks. I am attempting to write an invoicing system that uses a MySQL database to store invoices, product pricing, and customer contact info. I would like to automatically fill in the customer's contact info after typing in the first and last name, and the product pricing info after typing in the product name. From my searches I've found that the onChanged event may be what I'm looking for. However, this only seems to reference JavaScript and AJAX. Is there a way to use this just with PHP? I've done some searching but have very little understanding of JS and AJAX.

Just to make sure my question is clear, I don't want the user to have to click a button to fill in the data, and I don't want to have to reload the page. I just want the customer contact info and pricing info to automatically fill in from the database after tabbing out of the corresponding name text box. I.E. type in first and last name, press Tab, then the phone and address automatically fill in their own text boxes. Or type a product name and press tab, and the pricing info automatically fills in its own text box.

Sorry for being so long-winded. Any suggestions? Is there any code I should post that would help? I can submit the form and update my database w/o any problems, I just have no clue where to begin on this one.

Thanks,
Dybs
Nov 18 '07
16 39489
ak1dnar
1,584 Recognized Expert Top Contributor
If possible, I'd like to do this with pure PHP, but if it's easier to do w/ php-ajax I'm certainly willing to learn it.
With pure Php you cannot get the records with out reloading your page. (Read your Original Post, You were looking for a solution for AutoFilling input boxes with out using a Button)
So the only option is, you have to use JavaScript and XML on this.

As for the document.getEle mentByID() line in your last post, would those go in the stateChanged() function in the javascript file from the examples on w3schools?
Yes
Or would those go in the php file after my sql query returns my results?
No

And I think I can help you more on this. Please post the codes that you have used so far. Thanks.
Nov 19 '07 #11
dybalabj
9 New Member
Ajaxrand,

Thanks so much for your help. I apologize in advance for posting so much code, but you asked for it :)

Here is the segment of code for the product lines in the form:

[PHP]$i=1;
echo "<script src='autofill_p rice.js'></script>";
while($i<=5){
echo "$i";
echo "<input type='text' size=5 name='quantity$ i'> &nbsp ";
echo "<input type='text' size=90 name='product$i ' onblur='showPri ce(this.value, $i)'>&nbsp ";
echo "<input id = 'product$i' type='text' size=6 name='unit$i'> &nbsp ";
echo "<input type='text' size=10 name='total$i'> <br>";
$i++;
}[/PHP]

This is similar to the code I posted in #5. Here is the javascript I have so far for the products. The main functions of concern here would be showPrice() and stateChanged(), of course:

Expand|Select|Wrap|Line Numbers
  1. var xmlHttp
  2. var num
  3. function showPrice(str, i)
  4. xmlHttp=GetXmlHttpObject()
  5. num=i
  6. if (xmlHttp==null)
  7.  {
  8.  alert ("Browser does not support HTTP Request")
  9.  return
  10.  }
  11. var url="get_price.php"
  12. url=url+"?q="+str
  13. url=url+"&id="+i
  14. url=url+"&sid="+Math.random()
  15. xmlHttp.onreadystatechange=stateChanged
  16. xmlHttp.open("GET",url,true)
  17. xmlHttp.send(null)
  18. }
  19.  
  20.  
  21. function stateChanged() 
  22. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  23.  { 
  24.  document.getElementById("price"+num).innerHTML=xmlHttp.responseText 
  25.  } 
  26. }
  27.  
  28. function GetXmlHttpObject()
  29. {
  30. var xmlHttp=null;
  31. try
  32.  {
  33.  // Firefox, Opera 8.0+, Safari
  34.  xmlHttp=new XMLHttpRequest();
  35.  }
  36. catch (e)
  37.  {
  38.  //Internet Explorer
  39.  try
  40.   {
  41.   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  42.   }
  43.  catch (e)
  44.   {
  45.   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  46.   }
  47.  }
  48. return xmlHttp;
  49. }
Any finally here's the PHP that gets the product info out of the MySQL database and attempts to insert it into the form:

[PHP]<?php
include "connect.ph p";

$q=$_GET["q"];
$i=$_GET["id"];

$sql="SELECT unit_price FROM Product WHERE product_name = '".$q."'";

$result = mysql_query($sq l);

$row = mysql_fetch_arr ay($result);

echo "<?xml version='1.0' encoding='ISO-8859-1'?>
<price>";
echo "<product$i >" . $row['unit_price'] . "</product$i>";
echo "</price>";

mysql_close();
?>[/PHP]

Earlier attempts using the <div> tag did at least update the unit_price field in the form but all updates occurred in the same spot (the first product line). With the code I just posted, I get no updates at all, and no errors or warnings. I do have my php.ini file set to show all warnings. Thanks again for taking the time to look at this. If you need me to post anymore code, let me know.

Thanks,
Dybs
Nov 19 '07 #12
ak1dnar
1,584 Recognized Expert Top Contributor
Expand|Select|Wrap|Line Numbers
  1.   document.getElementById("price"+num).innerHTML=xmlHttp.responseText
by using this line you want to print back the price of the product, right? but in here down below, there is no element named "price<num> ".
[PHP]$i=1;
echo "<script src='autofill_p rice.js'></script>";
while($i<=5){
echo "$i";
echo "<input type='text' size=5 name='quantity$ i'> &nbsp ";
echo "<input type='text' size=90 name='product$i ' onblur='showPri ce(this.value, $i)'>&nbsp ";
echo "<input id = 'product$i' type='text' size=6 name='unit$i'> &nbsp ";
echo "<input type='text' size=10 name='total$i'> <br>";
$i++;
}[/PHP]

and also from the server side, you are generating XML out put. But your client side javascript is wrong here because you are using responseText. Instead of you have to use responseXML.

And on the server side php script that you printing the XML file also you have to do some changes. print the xml nodes in a while loop and put this line out side the loop.
Expand|Select|Wrap|Line Numbers
  1. echo '<?xml version="1.0" encoding="ISO-8859-1"?>
  2. <your_node_name>';
Nov 20 '07 #13
dybalabj
9 New Member
I tried making most of the changes you suggested except for the loop idea, but nothing is getting updated in my form at this point. For now I'd like to focus on the customer section, then once that's working I can go back to the product lines.

Btw, this is for a school project in my Databases course, and I need a working demo by Friday, Nov 30 :)

Anyway, here's the form for the customer info:
[PHP]<form action="studio_ update.php" method="post">
<?php
echo "<script src='autofill_c ustomer.js'></script>";
echo "Customer Info:<br>";
echo "Last:
<input type='text' size=20 name='last' onblur='showCon tact(first.valu e, this.value)'> &nbsp &nbsp &nbsp ";

echo "First:
<input type='text' size=20 name='first' onblur='showCon tact(this.value , last.value)'><b r>";

echo "Phone 1: &nbsp
<input id='cust_phone1 ' type='text' size=12 name='phone1'> <br>";

echo "Phone 2: &nbsp
<input id='cust_phone2 ' type='text' size=12 name='phone2'> <br>";

echo "Address: &nbsp
<input id='cust_addres s' type='text' size=50 name='address'> <br>";

echo "<hr>";[/PHP]
The form close tag is further down after the products.

Below is my javascript code:
Expand|Select|Wrap|Line Numbers
  1. var xmlHttp
  2.  
  3. function showContact(first, last)
  4. xmlHttp=GetXmlHttpObject()
  5. if (xmlHttp==null)
  6.  {
  7.  alert ("Browser does not support HTTP Request")
  8.  return
  9.  }
  10. var url="get_customer.php"
  11. url=url+"?f="+first
  12. url=url+"&l="+last
  13. url=url+"&sid="+Math.random()
  14. xmlHttp.onreadystatechange=stateChanged 
  15. xmlHttp.open("GET",url,true)
  16. xmlHttp.send(null)
  17. }
  18.  
  19. function stateChanged() 
  20. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  21.  { 
  22.  document.getElementById("cust_phone1").innerHTML=xmlHttp.responseXML 
  23.  document.getElementById("cust_phone2").innerHTML=xmlHttp.responseXML
  24.  document.getElementById("cust_address").innerHTML=xmlHttp.responseXML 
  25.  } 
  26. }
And finally my server side PHP script to get the customer info:
[PHP]<?php
include "connect.ph p";

$first=$_GET["f"];
$last=$_GET["l"];

$sql="SELECT customer_id, phone1, phone2 FROM Customer WHERE first = '".$first."' AND last = '".$last."'" ;

$result = mysql_query($sq l);

// Row contains the phone numbers
$row = mysql_fetch_arr ay($result);
$id = $row['customer_id'];

// Addr contains only the address
$sql = "SELECT address FROM Customer_Addres s WHERE customer_id = '".$id."'";
$addr = mysql_query($sq l);
$addr = mysql_fetch_arr ay($addr);

echo "<?xml version='1.0' encoding='ISO-8859-1'?>
<person>";

echo "<cust_phon e1>" . $row['phone1'] . "</cust_phone1>";
echo "<cust_phon e2>" . $row['phone2'] . "</cust_phone2>";
echo "<cust_address> " . $addr['address'] . "</cust_address>";

echo "</person>";
mysql_close();
?>[/PHP]

So here's my understanding of what should happen (which was sorta working before, just the updates were in the wrong location on the form):
1) I enter a first or last name, and tab out of that box.

2) The javascript function showCustomer() executes w/ the contents of the firstname and lastname text boxes, and sets the phone and address text boxes to be filled by the results of the responseXML generated by the PHP form.

3) The PHP script gets called, which gets the phone and address out of the database, and sends back an XML document w/ the appropriate info. This then gets parsed (by I don't know what exactly) and filled into the appropriate fields.

As I said, no text fields are being updated now. I think I've made all the changes you suggested (w/o the loop for the product at this point, of course), but I would think the customer should still be getting updated now. I don't see how a loop would be practical for this particular section. Should my echo <id_name> row[id] </id_name> lines include the <input type='text'> tags as well?

As for the products, since each product line has its onBlur event set to showPrice(str, i), I pass the line number into the function, so my PHP script should only update the most recently changed product line, not all the lines every time.

Again, any help or insight is appreciated.

Dybs
Nov 20 '07 #14
ak1dnar
1,584 Recognized Expert Top Contributor
I tried making most of the changes you suggested except for the loop idea
Yes for this script no need to put your XML declaration out side the loop. May be its giving only one record based on the Where clause. But there might be possibilities like, there will be two peoples/products with the same name. Then since you have put this XML declaration and the root xml element within the Loop they will repeat. That's what I asked you to move it to the out side.
I am sorry to say this too, as my understandings you are not reading the Tutorial completely. These are some points you hae to refer.

And Please note that we have some strict rules on posting course works, home work questions. you may better to read this too.
Posting Homework or Coursework Questions and Answers
This site is not a place where you can get your homework and course work done for you. Ignoring the questionable morals of getting someone else to do your work towards a formal qualification you will learn a lot more by attempting the problem yourself, then asking for help with the bits that are not working. You will be more likely to get help if you appear to have made an attempt at the problem yourself.
Nov 21 '07 #15
dybalabj
9 New Member
I apologize for not reading the notice about posting homework problems. I did not mean to give the impression I am trying to get this work done for me. I am just trying to learn how to properly code this solution, and unfortunately the only teachers I can go to don't know much more than I do and haven't been much help. I'm more just trying to learn to proper syntax for what I want to accomplish, not have someone do the work for me. I will certainly read the links you sent, and thanks very much for you help so far.
Nov 21 '07 #16
dybalabj
9 New Member
Thanks again for your help so far. In the interest of time, I've decided to drop the autofill feature as it is, and break the form up into 3 different submissions: get customer info, get price info, and add invoice to database. The first 2 technically reload the form, but keep the already entered data, plus adding the information from the query. It may not be the most responsive and efficient solution, but it works well enough for the purposes of my project.

Thanks again for your help, and I apologize again for seeming so dependent and unwilling to work. As I mentioned in my previous post, web programming is something I am extremely unfamiliar with and am having problems figuring out where to really begin. Give me a c++ program any day :) FYI, I was able to get this feature working in a little less than an hour in .Net.

Dybs
Nov 22 '07 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

1
18531
by: shortbackandsides.no | last post by:
I'm having a lot of difficulty trying to persuade the Google toolbar autofill to act consistently, for example ======================= <html><head> <title>autofill test</title> </head><body> <form method="POST" action=""> 1 email <input type="text" name="email"><br> 2 name <input type="text" name="name"> <br>
1
2549
by: Dave | last post by:
Hi All, Just getting started with ASP (NOT .NET) and have a question: I have a basic form and I'm trying to add some functionality to it. I want a user to be able to select a product from a list box. After this product is selected have another text box, ProductID update to reflect the product number. In VB I would use an OnChange type thing. Can anyone point me how to do
2
1859
by: jenese | last post by:
Hi! I've searched the forum and the net for the answer of, probably an easy question for the experienced.... I need to limit the amount of text to 50 first characters when looping out the data from a mysql text-table. How and where do I attack this problem? :confused: Thanks! :cool:
4
15848
by: HTS | last post by:
I have written a membership database application (PHP + mySQL) and need to prevent autofill from filling in fields in a member record edit form. I know I can turn off autoFill in my browsers, I want a away to prevent it within the form itself. Is there any standard way to "tell" a browser not to autofill the fields on a particular form?
0
2057
by: Randy | last post by:
Hi, I have some comboboxes that are created dynamically at run time based on user actions. I found a procedure on a message board to autofill the combobox text from the dataview that the comboboxes are bound to. It works perfectly on the comboboxes that I have created at design time, but the ones that I create runtime behave differently. The problem is that when the user tabs onto the combobox, the box stays blank, which is fine. ...
3
2232
by: Richard | last post by:
Hi all. I have a PHP form for entering data on-line into a mySQL table.. Because of the intended search facility, I require one field in the form to be completed with exact and precise item names and spelling. In testing, I had achieved this with look-up tables. Ideally I would like the selected item from one of five drop-down lists to autopopulate the form text field when selected. Alternatively at least the option of copy and paste....
1
15411
by: Pazeh | last post by:
Hello, a first timer here! stumbled upon one of the threads hear while searching on google & the feedback was awesome so I decided to jump in & ask my Q! I'm a newbie in AJAX, but I know my way pretty well in PHP / MySQL. What is the best/easiest practice that you have used to autocomplete a field & autofill a form? Here is the senario. I have a MySql table with contacts details, I want that when I start filling the name of the contact...
6
38632
by: Shaft11 | last post by:
I have searched and searched and cannot seem to find an answer that fits my needs. Hopefully you can help. I have a database that stores names,addresses, etc. I am trying to get it to where I start typing the last name it will 'suggest' names that are already in the table. ex. If the last name is "Johnson", When I start typing "Jo" it will automatically complete as i type. Any Idea's? Thank you Shaft11
0
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8835
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.