Solved

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

Posted on 2009-04-03
15
2,057 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
 
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

747 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now