0

I've got what I think must be a pretty simple question, but it's my first time doing something like this.

Here's my situation. I have a simple database. It's a dictionary of words. I want to have a form that I can enter a word into. Once I do that, I want to show the results on that page (or another page, if that's the easier or 'normal' way to do that).

Here's the code I have so far:

<form name="word" method="post" action="notSureWhatToPutHere"><fieldset>
<legend>Type your word here:</legend>
  <input type="text" name="enterWord" id="wotd" size="77"> <input type="submit" name="Submit" value="Submit" id="submitwotd">
</fieldset>
</form>
<?
$query="SELECT * FROM Dictionary WHERE word='']";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

$i=0;
while ($i < $num) {

$Word=mysql_result($result,$i,"Word");
$Definition=mysql_result($result,$i,"Definition");

echo "<b>$Word:</b> $Definition<br>";

$i++;
}

?>

This code works fine if I have the right value (the word) here:

$query="SELECT * FROM Dictionary WHERE word='theWord']";

But I want to use a form to pass the entered value to that query.

Any pointers? All the tutorials I found online instructed how to pass information to a database with a form, not retrieve information with a form.

Thank you!

2
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by effu
1

You just need to declare that variable from the form.

<form name="word" method="post" action="notSureWhatToPutHere"><fieldset>
<legend>Type your word here:</legend>
  <input type="text" name="enterWord" id="wotd" size="77"> <input type="submit" name="Submit" value="Submit" id="submitwotd">
</fieldset>
</form>


<?PHP

//declare the variable POSTED from the form
$word = $_POST['enterWord'];

//if $word is not blank then proceed.
if ($word != '') {

$query="SELECT * FROM Dictionary WHERE word='$word']"; //notice WHERE word='$word'
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

$i=0;
  while ($i < $num) {

  $Word=mysql_result($result,$i,"Word");
  $Definition=mysql_result($result,$i,"Definition");

  echo "<b>$Word:</b> $Definition<br>";

$i++;
  } 

//else echo error if the word was blank
} else {
  echo '<p style="color: red">You did not enter a word. Please try again.</p>';
}

?>
Votes + Comments
Thank you! :)
0

Thank you! Yes, the trick was passing the information from the form to a variable.

For my code, I had to remove the ] to get it working; I'm not sure why. Like this:

This worked:

$query="SELECT * FROM Dictionary WHERE word='$word'"; //notice WHERE word='$word'

This didn't work:

$query="SELECT * FROM Dictionary WHERE word='$word']"; //notice WHERE word='$word'

Thanks so much! It's working now. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.