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!

Recommended Answers

All 3 Replies

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>';
}

?>
commented: Thank you! :) +2

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. :)

No problem,sorry about the typo.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.