Jump to content

Captcha not working SQL + PHP + HTML


MLL
Go to solution Solved by MLL,

Recommended Posts

Hi all!

I am new so don't hate if I write something in a bad way. Thanks.

I have a "logical captcha" which is like a quiz.

 

Here is my code. I don't know what is wrong with it :(

<?php

    $database_db="general";
    $user_db="root";
    $password_db="somepass";
    $host_db="localhost";

    $link = mysqli_connect($host_db, $user_db, $password_db, $database_db);

    if (mysqli_connect_errno()) 
    {
        die ("couldnot connect: ".mysqli_connect_error());
        exit();
    }   

$answer = $_POST['answer'];
if (array_key_exists("answer", $_POST) AND array_key_exists("question", $_POST))
{
    $id = intval($_POST['question']);
        $sql="SELECT question, answer FROM captcha WHERE question='$id' AND answer='".mysqli_real_escape_string($link, $answer)."'";
        $result = mysqli_query($link, $sql)  or exit('$sql failed: '.mysqli_error($link)); 
        $num_rows = mysqli_num_rows($result);
        if($num_rows > 0)
        {
            header("Location: success.php");
        } 
        else 
        {
            header("Location: error.php");
        }
        exit;
    }
    else
    {
        $query = "SELECT id, question FROM `captcha` ORDER BY RAND() LIMIT 1";
        if ($result = mysqli_query($link, $query))
        {
            if ($row = mysqli_fetch_assoc($result)) 
            {
                $id = $row["id"];
                $question = $row["question"];
            }
        }
    }

?>
<html>
    <body>
        <form method="post">
            <?php echo $question; ?><br />
            <input type="hidden" name="question" id="question" value="<?php echo $id; ?>" />
            <input type="text" name="answer" id="answer" /><br />
            <input type="submit" name="submit" value="submit" /><br />
        </form>
    </body>
</html>

So the problem is that it always redirects to error.php, even if I enter the right answer

Link to comment
Share on other sites

I don't think $_POST['question'] and $_POST['answer'] contain the values that you expect. I don't see anything wrong with your code, so if it is never returning anything from the database, then the criteria probably isn't matching any rows. Either that or you don't have the data you expect in your table.

 

Also, question appears to be an integer, so you don't need quotes around it in the query. It should still work though.

Link to comment
Share on other sites

1) you shouldn't have to keep listing $link in your mysqli_ calls

2) Your if statements based on equality will always evaluate to true, because you're using an assignment operator = instead of comparison == since you can assign any value (or none) to $result, it will always evaluate the assignment as true.

3) Whenever you run into an issue where you're not getting data, or getting data you don't expect, output your query and take a look at it. In this case it would show you that you're quoting the table name, which is a no-no.  quotes are for literal strings only in SQL, your query right now is trying to pull fields from a literal string instead of the table with the name specified in the literal string.

Edited by seandisanti
Link to comment
Share on other sites

1) you shouldn't have to keep listing $link in your mysqli_ calls

2) Your if statements based on equality will always evaluate to true, because you're using an assignment operator = instead of comparison == since you can assign any value (or none) to $result, it will always evaluate the assignment as true.

3) Whenever you run into an issue where you're not getting data, or getting data you don't expect, output your query and take a look at it. In this case it would show you that you're quoting the table name, which is a no-no.  quotes are for literal strings only in SQL, your query right now is trying to pull fields from a literal string instead of the table with the name specified in the literal string.

 

 

 

Thanks but I don't fully understand what you wrote. I am a VERY beginner developer. Can you write the things in my code? Also if it is possible, with comments, so I can learn from it. Thank you very much :)

Edited by MLL
Link to comment
Share on other sites

Like I said, the problem is with the data correlation. Your query has:

$id = intval($_POST['question']);
[..]
WHERE question='$id'

You set $id to an integer, then test it against a string. Based on your screenshot, there are no values of "question" that would match an integer comparison. That is why you never get any rows from your query.

 

Assuming $_POST['question'] actually contains an id, you query should be against the id column:

WHERE id=$id
Link to comment
Share on other sites

Thanks but I don't fully understand what you wrote. I am a VERY beginner developer. Can you write the things in my code? Also if it is possible, with comments, so I can learn from it. Thank you very much :)

No problem.

 

 

1) you shouldn't have to keep listing $link in your mysqli_ calls

means mysqli_query($link, $query) can and probably should be written as mysqli_query($query)

 

 

2) Your if statements based on equality will always evaluate to true, because you're using an assignment operator = instead of comparison == since you can assign any value (or none) to $result, it will always evaluate the assignment as true.

Try this:

<?php
$a = 'a';
if ($a = 'b'){
    echo 'Should have used "=="';
} else {
    echo 'This will never echo because you are evaluating an assignment instead of an equality';
}
 

 

 

3) Whenever you run into an issue where you're not getting data, or getting data you don't expect...

When you're working with a database and get unexpected results (or none at all) your first troubleshooting step should be to verify your query after it's compiled.  There are several ways to do it, but I typically just die($sql); right after my query is assigned to variable $sql.  Then when i go to the page, it outputs the query as passed to the database.  If i can't spot the error (usually it's something silly like a missing space in the concatenation  like 'SELECT idFrom table') then I will copy the whole query and run it on its own in phpmyadmin, or mysql console directly.  If it runs successfully but returns no results or bad results then it's a logic issue.  If it errors out, then it's a syntax issue, and it will usually give you a clue where to look for it.

Link to comment
Share on other sites

Just to be clear, you DO need to pass the mysqli connection resource when calling mysqli_query(). You do NOT need to if you are using a variable in object context, which he is not.

 

http://us3.php.net/manual/en/mysqli.query.php

Thanks for the clarification, when I used mysqli I typically used objects and didn't even think about it being handled differently in procedural context. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.