Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2009-04-03
15
2,064 Views
Last Modified: 2013-12-12
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

0
Comment
Question by:delphibeginner
  • 8
  • 7
15 Comments
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24059285
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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24059304
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
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24059325
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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24059392
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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24059465
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
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24059519
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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24059774
I get a parse error on the select line:

$sql = 'SELECT email FROM `'.$hesk_settings['db_pfix'].'names` WHERE `naam` = ($_POST['naam'])';
0
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24059894
You have not done the quotes properly.

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

Olly.
0
 
LVL 1

Author Comment

by:delphibeginner
ID: 24060017
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
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24060852
"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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24084361
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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24084500
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
 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24084799
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
 
LVL 1

Author Comment

by:delphibeginner
ID: 24084938
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
 
LVL 10

Accepted Solution

by:
ollyatstithians earned 125 total points
ID: 24095044
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

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question