Shawn
Shawn

Reputation: 147

echoing to text box in php

I'm trying to do something simple to learn how to do a query and then put the answer into a box. I have a HTML file that looks like this:

<html>
<head>
<title>Test</title>
</head>
<body>
<form action="results.php" method="post">Search: <input name="term" type="text" /><br />    
<input name="submit" value="Submit" type="submit" />
<p>Answer: <input name="answer" type="text" /></p>
</form>
</body>
</html>

And the php code is:

<?php
$hostname = 'host.com';
$username = 'ratetable';
$password = 'mypassword';
$term = (int) $_GET['term'];

try 
{
   $db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
   //echo 'Connected to database<br />';

   foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $term . ' ORDER BY mileage DESC LIMIT 1') as $row) {
       echo "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>";
   }
}         
catch (PDOException $e) {
       echo $e->getMessage();
       throw($e);
   }
?>

So I'm trying to put ratepermile, a field in the database, into the 'answer' text box. What I get is the screen clears, but no form and no result, even after I comment out the 'connected to database' echo line and use something that I know exists in the database.

How can I keep the form on screen and echo to the text box?

Thanks for looking.

Upvotes: 0

Views: 247

Answers (3)

Kannan Rajendran
Kannan Rajendran

Reputation: 220

You can use $_REQUEST in order to avoid these confusions. Whether you use method="post" or method="get", you can fetch the value through this.

Upvotes: 0

Zac
Zac

Reputation: 1635

As well as the above POST issue. If you wish to keep the form on the page and not reload the page you need to look into AJAX.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227290

Your form is POSTing the data (method="post"), but your PHP script is looking in the $_GET aray.

You need to get the data from $_POST instead.

$term = (int) $_POST['term'];

Upvotes: 3

Related Questions