Forum Moderators: coopster
How would I make a code that checks if a person guessed the right word that is stored in the database.
Example code:
<?php
include('mysql_connect.php');
$guess = $_GET['op'];
if($guess == 'guess'){
$word = $_POST['word'];
$query = "SELECT * FROM names WHERE name='$word'";
$result = mysql_query($query);
if (!$result ¦¦ mysql_num_rows($result) < 1){
$feedback = "<font color=\"red\" size=\"+1\">Sorry, wrong word...</font>";
print $feedback;
}
else{
if(mysql_result($result, 0, "word")){
print "you got it right!";
}
else{
print "<font color=\"red\" size=\"+1\">Sorry.</font>";
}
}
}
else{
$guess = null;
echo "<strong>Guess the word!</strong><br />";
}
?>
<FORM METHOD="POST" ACTION="?op=login">
word: <input type="text" name="word"><br>
<input type="SUBMIT" value="Submit">
</FORM>
but I don't understant the mysql_result and mysql_num_rows so the code doen't work
Help please.
thanks
electricoean
<?php
//conncet to db
//select database
function getForm() //create a simple function
{
echo '<form name = "someGuess" action = "guess.php" method = "POST">';
echo '<input type = "text" name = "guess" >';
echo '<input type = "submit" name = "guessSubmit" value = "Take a Guess">';
echo '</form>';
}//end getform
if (isset($_POST['guessSubmit'])) //process the form if the button was pressed
{
$getGuess = mysql_query("SELECT guess FROM GuessTable WHERE guess = '{$_POST['guess']}' ")or die(mysql_error());
$guess = mysql_fetch_array($getGuess);//get the value of the query
if ($guess['guess'] == $_POST["guess"])//test query results against form results
{
echo "Your guess was correct";
}//end if
else
{
echo "sorry incorrect guess";
}//end else
}//end if processing
else//get the form
getForm();
?>
--Nick
I understand everything in that code except for the line that says:
if ($guess['guess'] == $_POST["guess"])
if i changed $guess = mysql_fetch_array($result); to $fetch_array = mysql_fetch_array($result);
then the if stament would now be: if ($fetch_array['guess'] == $_POST["guess"])
and does that means that if the fetch_aray variable (useing ['guess'] in some way i don't get.) and sees if it equal to the the word someone guessed?
if someone could explain this line that would be great.
thanks,
electricocean
so our variable $result will look like this now:
result[Lname] -> "last name here"
result[Mname] -> "middle name"
result[Fname] -> "first name here"
So we use the column names of what we selected (in the query) as the keys instead of just integers as you normally see: result[0], result[1], result[2]
Now, if the query returned more than one row and we wanted to fetch all the results and display them then just loop until no more rows
$result = mysql_fetch_array($getResult);
while($result)
{
echo $result[Fname];
echo $result[Mname];
echo $result[Lname];
$result = mysql_fetch_array($getResult);
}
$result should return a NULL when you run out of rows...Sorry for the late reply.
--Nick