Hi guys,

Im really hoping someone can shed some light and point me in the right direction, I have a form that works just fine but now im trying to make it so that the customer details section of the form can be automatically filled in by selecting from a drop down a previously submitted customer that is in the database.

I have been kind of in a round about way been able to get the dropdown to populate from the database using dreamweavers many tools and can even get some of the data to transfer into the fields however it only populates the first database entry and doesnt allow it to be changed.

Any help would be greatly appreciated.

Hi.

I stay away from Dreamweaver's overrated tools like the plague... so I won't be able to help you with those.

But I can show you how to do this in PHP code:

<?php
// Establish a DB connection
$dbLink = new mysqli('localhost', 'usr', 'pwd', 'db_name');
if(mysqli_connect_errno()) {
    printf("Database connection failed: %s", mysqli_connect_error());
    exit;
}

// Initialize an array containing posible
// inital values for the form fields
$initalValues = array(
    'name' => '',
    'email' => '',
    'whatever' => ''
);

// Check if a previous user has been selected
// from the dropdown.
($previousID = @$_POST['PreviousCustomer']) or $previousID = null;
if($previousID) {
    // Get the data for this customer.
    $customerID = $dbLink->real_escape_string($_POST['PreviousCustomer']);
    $sql = "SELECT name, email, whatever FROM customer WHERE id = {$customerID}";
    $result = $dbLink->query($sql);

    if($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $initalValues = $row;
    }
    else {
        user_error("The given customer id did not match any customer.", E_USER_NOTICE);
    }

    @$result->close();
}

// Open the form
echo '<form id="formID" action="otherFile.php" method="post">';

// Print the <select> box.
// Note that I use JavaScript to alter the action
// of the <form> element when an option is selected, 
// so that it reloads this page rather than go on to 
// the submission page, and then submit it.
echo '  <select name="PreviousCustomer"
            onchange="if(this.value != \'\') {
                        document.getElementById(\'formID\').action=\'?\';
                        document.getElementById(\'formID\').submit();
                     }"
        >';
echo '    <option value=\'\'>- Select -</option>';

// Print a list of previous customers as
// options for the <select>
$sql = "SELECT id, name FROM customer";
$result = $dbLink->query($sql);
while($row = $result->fetch_assoc()) {
    $selected = ($row['id'] == $previousID ? 'selected="selected"' : '');
    echo "<option value='{$row['id']}' {$selected}>{$row['name']}</option>";
}

// Close the <select> and print the rest of the form
echo '</select><br />';
echo <<< HTML
    Name: <input type="text" name="name" value="{$initalValues['name']}" /><br />
    Email: <input type="text" name="email" value="{$initalValues['email']}" /><br />
    Whatever: <input type="text" name="whatever" value="{$initalValues['whatever']}" /><br />
    <input type="submit" />
</form>
HTML;

// Close the database link
$dbLink->close();
?>

Thanks for replying I can't seem to get the code you supplied to work, I'm getting parse error with the "echo <<< HTML" line??

That's weird. I copied that code directly from my test server, where it ran fine.

Which version of PHP are you using?
Could you post the exact error here?

Try removing the space between the <<< and HTML.
Making it: echo <<<HTML

Parse error: parse error in C:\wamp\www\powercart\orderentry.php on line 372

// Close the <select> and print the rest of the form
echo '</select><br />';
echo <<<HTML   
	Name: <input type="text" name="name" value="{$initalValues['contact']}" /><br />    
	Email: <input type="text" name="email" value="{$initalValues['email']}" /><br />    
	Whatever: <input type="text" name="whatever" value="{$initalValues['company']}" /><br />    
	<input type="submit" />
</form>
HTML;

Ok so I attached the file I'm working with perhaps it can give a better illustration of what it is im trying to do, the customer database has details for customers already entered so instead of having to re-enter everytime i'm trying to get a dynamic dropdown with the company name in it and when you select it, it fills in the customer fields so the order can be submitted essentially.

I really appreciate all your help.

Attachments
<?php # Script 7.3 - orderentry.php
include ('style.html');
$page_title = 'Order Entry';

// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

	$errors = array(); // Initialize error array.
	
	// Trim Company
	{
		$co = trim($_POST['company']);
	}

	// Trim Contact
	{
		$cn = trim($_POST['contact']);
	}

	// Trim Address
	{
		$ad = trim($_POST['address']);
	}

	// Trim Address2
	{
		$ad2 = trim($_POST['address2']);
	}

	// Trim City
	{
		$ct = trim($_POST['city']);
	}

	// Trim State/Province
	{
		$sp = trim($_POST['state_prov']);
	}


	// Trim Zip/Postal
	{
		$zp = trim($_POST['zip_postal']);
	}
	
	// Trim Country
	{
		$cou = trim($_POST['country']);
	}


	// Trim Phone
	{
		$ph = trim($_POST['phone']);
	}

	// Trim Email
	{
		$em = trim($_POST['email']);
	}


	// Trim Fax
	{
		$fx = trim($_POST['fax']);
	}

	// Trim Tax ID
	{
		$tx = trim($_POST['tax_id']);
	}

	// Trim Shipping Company
	{
		$cos = trim($_POST['sh_company']);
	}

	// Trim Shipping Contact
	{
		$cns = trim($_POST['sh_contact']);
	}

	// Trim Shipping Address
	{
		$ads = trim($_POST['sh_address']);
	}

	// Trim Shipping Address 2
	{
		$a2s = trim($_POST['sh_address2']);
	}


	// Trim Shipping City
	{
		$cts = trim($_POST['sh_city']);
	}


	// Trim Shipping State/Province
	{
		$sps = trim($_POST['sh_state_prov']);
	}

	// Trim Shipping Zip/Postal
	{
		$zps = trim($_POST['sh_zip_postal']);
	}
	
	// Trim Shipping Country
	{
		$cous = trim($_POST['sh_country']);
	}

	// Trim Shipping Phone
	{
		$phs = trim($_POST['sh_phone']);
	}

	// Trim Shipping Email
	{
		$ems = trim($_POST['sh_email']);
	}

	// Trim Shipping Fax
	{
		$fxs = trim($_POST['sh_fax']);
	}

	// Trim Order Date
	{
		$dt = trim($_POST['date']);
	}

	// Trim Order P.O.
	{
		$po = trim($_POST['po']);
	}

	// Trim Invoice Date
	{
		$idt = trim($_POST['invoice_date']);
	}

	// Trim Invoice Number
	{
		$in = trim($_POST['invoice']);
	}

	// Trim Sent to Manufacturer
	{
		$mfg = trim($_POST['sent_mfg']);
	}

	// Trim Requested Ship Date
	{
		$re = trim($_POST['req_date']);
	}

	// Trim Final Ship Date
	{
		$fn = trim($_POST['final_date']);
	}

	// Trim Shipped Via
	{
		$sh = trim($_POST['shipped_via']);
	}

	// Trim Tracking #
	{
		$tr = trim($_POST['tracking']);
	}

	if (empty($errors)) { // If everything's okay.
	
		// Register the user in the database.
		require_once ('mysql_connect.php'); // Connect to the db.
		
		// Make the query.
		$query = "INSERT INTO customers (customer_id, company, contact, address, address2, city, state_prov, zip_postal, country, phone, email, fax, tax_id) VALUES ('', '$co', '$cn', '$ad' , '$ad2', '$ct', '$sp', '$zp', '$cou', '$ph', '$em', '$fx', '$tx')";
		$result = @mysql_query ($query); // Run the query.
		$customer_id = mysql_insert_id();
		
		$query = "INSERT INTO shipping (shipping_id, sh_company, sh_contact, sh_address, sh_address2, sh_city, sh_state_prov, sh_zip_postal, sh_country, sh_phone, sh_email, sh_fax, customer_id) VALUES ('', '$cos', '$cns', '$ads' , '$a2s', '$cts', '$sps', '$zps', '$cous', '$phs', '$ems', '$fxs', '$customer_id')";	
		$result = @mysql_query ($query); // Run the query.
		$shipping_id = mysql_insert_id();
		
		$query = "INSERT INTO orders (order_id, date, po, invoice_date, invoice, sent_mfg, req_date, final_date, shipped_via, tracking, shipping_id) VALUES ('', '$dt', '$po', '$idt' , '$in', '$mfg', '$re', '$fn', '$sh', '$tr', '$shipping_id')";
		$result = @mysql_query ($query); // Run the query.
		$order_id = mysql_insert_id();
		
		//$result = @mysql_query ($query); // Run the query.
		foreach($_POST as $key => $value)
	{
		//looping through all posted fields
		if(strpos($key, 'partid_') !== false)
		{
			//found a part field, need to find out the _x number, then insert the entire row
			$suffix = substr($key, -1); //this gets the _x number
			$partid = $_POST['partid_' . $suffix];
			$quantity = $_POST['quantity_' . $suffix];
			$desc = $_POST['desc_' . $suffix];
			$serial = $_POST['serial_' . $suffix];
			
			$query = "INSERT INTO parts_ordered (partid, quantity, `desc`, serial, order_id) VALUES ('$partid', '$quantity', '$desc', '$serial', '$order_id')";
			$result = mysql_query($query);
		}
	}
		if ($result) { // If it ran OK.
		
			// Send an email, if desired.
			
			// Print a message.
			echo '<h1 id="mainhead">Thank you!</h1>
		<p>Your entry has now been registered.</p><p><br /></p>';	
		
			// Include the footer and quit the script (to not show the form).
 
			exit();
			
		} else { // If it did not run OK.
			echo '<h1 id="mainhead">System Error</h1>
			<p class="error">Your entry could not be registered due to a system error. We apologize for any inconvenience.</p>'; // Public message.
			echo '<p>' . mysql_error() . '<br /><br />Query: ' . $query . '</p>'; // Debugging message.
 
			exit();
		}
		
		mysql_close(); // Close the database connection.
		
	} else { // Report the errors.
	
		echo '<h1>Error!</h1>
		<p class="error">The following error(s) occurred:<br />';
		foreach ($errors as $msg) { // Print each error.
			echo " - $msg<br />\n";
		}
		echo '</p><p>Please try again.</p><p><br /></p>';
		
	} // End of if (empty($errors)) IF.

} // End of the main Submit conditional.
?>
<script language="javascript">
			//add a row to the rows collection and get a reference to the newly added row
				var partsRowCount = 1; //stores the number of rows
		
			//add a new row to the table
			function addRow()
			{
				var namePrefix = "_" + (+partsRowCount + 1); //setup the prefix variable
				
				partsRowCount++; //increment the counter
				
				//add a row to the rows collection and get a reference to the newly added row
				var newRow = document.all("orderentry").insertRow();
				
				//add 3 cells (<td>) to the new row and set the innerHTML to contain text boxes
				
				var oCell = newRow.insertCell();
				oCell.innerHTML = "<input type='text' name='partid" + namePrefix + "'>";
				
				oCell = newRow.insertCell();
				oCell.innerHTML = "<input type='text' name='quantity" + namePrefix + "'>";

				oCell = newRow.insertCell();
				oCell.innerHTML = "<input type='text' name='desc" + namePrefix + "'>";
				
				oCell = newRow.insertCell();
				oCell.innerHTML = "<input type='text' name='serial" + namePrefix + "'>";			
			}
			
			//deletes the specified row from the table
			function removeRow(src)
			{
				/* src refers to the input button that was clicked.	
				   to get a reference to the containing <tr> element,
				   get the parent of the parent (in this case case <tr>)
				*/			
				var oRow = src.parentElement.parentElement;		
				
				//once the row reference is obtained, delete it passing in its rowIndex			
				document.all("orderentry").deleteRow(oRow.rowIndex);		
			}
		
		</script>
<style>

body {
margin:0 0 0 0;
font-family:"Verdana", Geneva, sans-serif;
font-size:10px;
width:700px;
}

#row {
width:695px;
}

.customerdrop {
	height:20px;
	font-family:"Verdana", Geneva, sans-serif;
	font-size:10px;
}
</style>
<?php
// Establish a DB connection
$dbLink = new mysqli('localhost', 'powercart', 'powercart', 'powercart');
if(mysqli_connect_errno()) {
	printf("Database connection failed: %s", mysqli_connect_error());    
	exit;
} 

// Initialize an array containing posible
// inital values for the form fields
$initalValues = array(
	'contact' => '', 
	'email' => '',
	'company' => ''
); 

// Check if a previous user has been selected
// from the dropdown.
($previousID = @$_POST['PreviousCustomer']) or $previousID = null;
if($previousID) {    

// Get the data for this customer.    
	$customerID = $dbLink->real_escape_string($_POST['PreviousCustomer']);    
	$sql = "SELECT name, email, whatever FROM customer WHERE id = {$customerID}";    
	$result = $dbLink->query($sql);     

	if($result->num_rows > 0) {        
		$row = $result->fetch_assoc();        
		$initalValues = $row;    
	}
		
	 else {
		 user_error("The given customer id did not match any customer.", E_USER_NOTICE);   
 	}     
	
	@$result->close();} 

// Open the formecho 
'<form id="formID" action="prderentry.php" method="post">'; 

// Print the <select> box.// Note that I use JavaScript to alter the action
// of the <form> element when an option is selected, 
// so that it reloads this page rather than go on to 
// the submission page, and then submit it.

echo '  <select name="PreviousCustomer"
			onchange="if(this.value != \'\') {
				document.getElementById(\'formID\').action=\'?\';
				document.getElementById(\'formID\').submit();
			}"
	>';
echo '<option value=\'\'>- Select -</option>'; 

// Print a list of previous customers as
// options for the <select>
$sql = "SELECT company, contact, email FROM customers";
$result = $dbLink->query($sql);
while($row = $result->fetch_assoc()) {    
	$selected = ($row['id'] == $previousID ? 'selected="selected"' : '');    
	echo "<option value='{$row['id']}' {$selected}>{$row['name']}</option>";
}


// Close the <select> and print the rest of the form
echo '</select><br />';
echo <<<HTML   
	Name: <input type="text" name="name" value="{$initalValues['contact']}" /><br />    
	Email: <input type="text" name="email" value="{$initalValues['email']}" /><br />    
	Whatever: <input type="text" name="whatever" value="{$initalValues['company']}" /><br />    
	<input type="submit" />
</form>
HTML; 

// Close the database link
$dbLink->close();
?>

<div id="body">
<form method="post" action="orderentry.php">
<table width="695" border="0" cellspacing="5" cellpadding="0" style="table-layout:fixed" id="orderentry">
  <tr>
    <td colspan="4"><strong>Customer Info:</strong>&nbsp;&nbsp;&nbsp; </td>
  </tr>
  <tr>
    <td>Company:</td>
    <td><label>
      <input name="company" type="text" id="company" />
    </label></td>
    <td>Contact:</td>
    <td><input name="contact" type="text" id="contact" /></td>
  </tr>
  <tr>
    <td>Address:</td>
    <td

Ok.

The problem is that you have a bunch of spaces after the heredoc delimiters.
There must be absolutely nothing behind either the echo <<< HTML , nor the HTML; .

Not even a single space.

This article has been dead for over six months. Start a new discussion instead.