PHP MYSQL fill input text from select menu (drop down)

I have a mysql database and a form made in php. What I want is the following:

The database contains the columns "naam" and "email". In the select menu in php the column naam is select (which works), but in the 2 input fields on the form I need to put in the naam and emailaddress.
For example, when I select: "Bart" from the select menu, in input field 1 there should be the name of Bart and in input field 2 there should be his email address.

I already have this code, but only the select menu works nothing appears in the input fields.

What did I miss?

Here is the code:
<?php
	require(HESK_PATH . 'inc/database.inc.php');
	hesk_dbConnect();
	$sql = 'SELECT * FROM `'.$hesk_settings['db_pfix'].'names`';
	$result = hesk_dbQuery($sql);
	while ($row=hesk_dbFetchAssoc($result))
	{
	    if ($_SESSION['c_name'] == $row['id']) {$selected = ' selected="selected"';}
	    else {$selected = '';}
	    echo '<option value="'.$row['id'].'"'.$selected.'>'.$row['naam'].'</option>';
	}
	{
		if( isset ($_POST['naam'])) {
		}
	$sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names`';
	$result = hesk_dbquery( $sql ); 
        if( $result !== false ) 
        { 
            if( hesk_dbNumRows( $result ) == 1 ) 
            { 
			}
		}
?>
 
<input type="text" name="email" size="40" maxlength="50" value="<?php echo stripslashes(hesk_input($_SESSION['c_email']));?>" />

Open in new window

LVL 1
delphibeginnerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ollyatstithiansCommented:
PHP will not update anything after the page has loaded, as it is a server-side scripting technology. You would have to select the name from a list, submit the form, and then you could look up the email address. Alternatively you could use AJAX to update the form without refreshing.

Olly.
0
delphibeginnerAuthor Commented:
Do you have a sample of how to do this? because I'm stuck.

I use xampp as server with php and mysql inside it.
0
ollyatstithiansCommented:
Sorry, I misread your code a bit.

Your second select query (line 15) needs a where clause to filter out the correct address:

select email from xxx.names where naam = {$_POST['naam']}

This will then return the email address for that name.

Olly.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

ollyatstithiansCommented:
Your end code is also missing to get the data from the query. I don't know what the "hesk" stuff is, so I have assumed the functions work the same as mysql functions.

Olly.
        $sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names`';
        $result = hesk_dbquery( $sql );
 
$record = hesk_dbFetchAssoc($result) or die('Could not find address.');
 
?>
<input type="text" name="email" size="40" maxlength="50" value="<?php echo stripslashes($record['email']);?>" />

Open in new window

0
delphibeginnerAuthor Commented:
Thanks I will test it. but I also saw something.

At the input line there was (hesk_input($_SESSION['c_email']), the thing is this has to be there (I tried to use it without but the script behind this page uses it also.

at the top of the page you see the code I posted first, there is a part "if ($_SESSION['c_name']", is there a way to implant this also (only then for c_email). Like the first query is for the select option, is there a way to make the input the same?
0
ollyatstithiansCommented:
That is a session variable. This means (forgive me if I am telling you how to suck eggs here) that it is carried over even if the page is refreshed. I don't know about the framework you are using, so I may be wrong, but it looks like you could just use the $_POST['naam'] variable to re-select the name. Nowhere in the code you have submitted is the variable $_SESSION['c_email'] set. If you want the email address you have retrieved from the database, you have to get it from the result set ($result) of the query.

Olly.
0
delphibeginnerAuthor Commented:
I get a parse error on the select line:

$sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = ($_POST['naam'])';
0
ollyatstithiansCommented:
You have not done the quotes properly.

$sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = \''.$_POST['naam'].'\'';

Olly.
0
delphibeginnerAuthor Commented:
thanks my mistake.

I dont know why, but now I get the message "address not found".

Some where there is still an error in the code.

Below is the code I have now:

<?php
	echo "<select name='naam'>";
	require(HESK_PATH . 'inc/database.inc.php');
	hesk_dbConnect();
	$sql = 'SELECT naam FROM `'.$hesk_settings['db_pfix'].'names`';
	$result = hesk_dbQuery($sql);
	while ($row=hesk_dbFetchAssoc($result))
	{
	    if ($_SESSION['c_name'] == $row['id']) {$selected = ' selected="selected"';}
	    else {$selected = '';}
	    echo '<option value="'.$row['id'].'"'.$selected.'>'.$row['naam'].'</option>';
	}
	echo "</select>";
	{
		if( isset ($_POST['naam'])) {
		}
	$sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = \''.$_POST['naam'].'\'';
	$result = hesk_dbquery( $sql ); 
	
$record = hesk_dbFetchAssoc($result) or die('Could not find address.');
	}
?>
	</td>
    </tr>
	<tr>
	<td style="text-align:right" width="150"></td>
	<td width="80%"><input type="hidden" name="email" size="40" maxlength="50" value="<?php echo stripslashes($record['email']);?>" /></td>
	</tr>

Open in new window

0
ollyatstithiansCommented:
"address not found" or "Could not find address."?

If it is the latter, then it is because line 20 is failing, which is either that the query failed or perhaps I have misunderstood the hesc database functions. You could try putting an "or die('Query failed')" at the end of line 18. This would tell you if the query was working.

Olly.
0
delphibeginnerAuthor Commented:
Sorry it took a while.
I've tested it but get no error and still a blank input field.

When I places the the line: "or die('Query field')" at the end of line 18 I dont get anything, so my guess is that line 20 is wrong.
But dont know what? Any suggestions?
0
delphibeginnerAuthor Commented:
I changed the code a bit.

But getting this error:

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in C:\xampp\htdocs\bestellingendatabase2\index.php on line 164

The error appears on the second query.

Here is the code:
<?php    
	require(HESK_PATH . 'inc/database.inc.php');
	hesk_dbConnect();
	$sql = 'SELECT * FROM `'.$hesk_settings['db_pfix'].'names`';
	$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
	
	//create selection list
        echo "<select name='naam'>\n";
                                        
        while($row = mysql_fetch_row($result))
        {
                $heading = $row[0];
                echo "<option value='$heading'>$heading\n";
        }
        echo "</select>";
        
		if( isset($_POST['naam']) ){// only show the rest of the fields if the drop down has been used
		
        //Secord Query
        $query = "SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = '\''.mysql_real_escape_string($_POST['naam']).'\'";
        $result = mysql_query($query) or die ('Error in query');
		$numrows=mysql_affected_rows();
		
		if($numrows>0){//only show the fields if there was a match. 
        $heading = mysql_fetch_row($result);
        
?>

Open in new window

0
ollyatstithiansCommented:
Line 20: You have mixed double and single quotes.
you wrote:
        $query = "SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = '\''.mysql_real_escape_string($_POST['naam']).'\'";
but single quoted version should be:
        $query = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = \''.mysql_real_escape_string($_POST['naam']).'\'';

Try getting an editor that highlights the code. It usually show this kind of thing up straight away.

Olly.
0
delphibeginnerAuthor Commented:
Thanks I missed that.

I've created a small test page, but the result is empty when clicking the submit button, when selecting a name from the dropdown list, in the field below the selection menu, it should show the email address of the selected person.

Here is the test code:
<?
//process form
?>
<html>
<head>
<title>DropDown</title>
</head>
 
<body>
<form name="events" method="post"  action="<?= $_SERVER['PHP_SELF']?>">
<table>
  <tr>
    <td> </td>
    <td>
      <?php 
        // open connection to MySQL server
        $connection = mysql_connect('localhost', 'root', '')
        or die ('Unable to connect!');
                                        
        //select database
        mysql_select_db('bestellingen') or die ('Unable to select database!');
                                        
        //create and execute query
        $query = 'SELECT naam FROM hesk_names';
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                                        
        //create selection list
        echo "<select name='naam'>\n";
                                        
        while($row = mysql_fetch_row($result))
        {
                $heading = $row[0];
                echo "<option value='$heading'>$heading\n";
        }
        echo "</select>";
        
		if( isset($_POST['naam']) ){// only show the rest of the fields if the drop down has been used
		
        //Secord Query
        $query = 'SELECT * FROM hesk_names WHERE `naam` = \''.mysql_real_escape_string($_POST['naam']).'\'';
        $result = mysql_query($query) or die ('Error in query');
		$numrows=mysql_affected_rows();
		
		if($numrows>0){//only show the fields if there was a match. 
        $heading = mysql_fetch_row($result);
        
      ?>
      
      
      
    </td>
  </tr>
  <tr>
    <td align="right" valign="top"><p>Email:</p></td>
    <td>
      <input type="text" name="email" id="email" class="heading" value="<?php echo $heading['email']; ?>">
    </td>
  </tr>
  <? 
  	}//end if numrows>0
	else
	{?>
  <tr>
    <td colspan="2">
      <p>Sorry, we have no information about that company</p>
    </td>
  </tr>
	<? }//end else
  } //end if isset post naam ?>
  <tr>
    <td> </td>
    <td>
      <input name="submit" type="submit" class="submitForm" value="Submit">
    </td>
  </tr>
</table>
</form>
</body>
</html>

Open in new window

0
ollyatstithiansCommented:
You have used the function mysql_fetch_row(), which returns a numeric key, in line 45, but then you refer to the field by name in line 56.

        $heading = mysql_fetch_row($result);
...
      <input type="text" name="email" id="email" class="heading" value="<?php echo $heading['email']; ?>">

Try changing the mysql_fetch_row() to mysql_fetch_assoc() to reference the fields by name.

Olly.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.