1

I'm making a site using self-made search engine and I want to put people's searchterms ($search) in a database. If $search is already in the database, I want the corresponding number (column Aantal in table) to go up by when. I succeed in adding a new searchterm in the table, but not updating one that is already in. It justs makes a new entry with Aantal = 1. Here's my code, searchterms is the name of the db and table, Zoekterm is the name of the columns were the searchterms go:

Sorry for my poor English :-)

if ($search != null) {
        $conn = new mysqli($servername, $username, $password, $dbname);
    if ("SELECT * FROM searchterms WHERE Zoekterm = '{$search}'"){
            $inserts = "INSERT into searchterms values('". $search . "', '" . 1 . "')";
            if ($conn->query($inserts) === FALSE) {
               echo "Error: " . $inserts . "</ br>" . $conn->error;
        }
    }
    elseif (!"SELECT * FROM searchterms WHERE Zoekterm = '{$search}'") {
        $i = mysqli_query($conn, "SELECT Aantal FROM searchterms WHERE Zoekterm = '{$search}'"); 
        $j = mysqli_fetch_row($i);
        foreach ($j as $k) {
            $k++;
            echo "<p>$k</p>";
        }
        $sql = "UPDATE searchterms SET Aantal='$k' WHERE Zoekterm = '$search'";
    }
    $conn->close();
}

1 Answer 1

1

This is totally wrong:

if ("SELECT * FROM searchterms WHERE Zoekterm = '{$search}'"){

if("string") will ALWAYS evaluate to true - those aren't queries. they're strings that happens to contain some characters that LOOK like sql. That text/sql doesn't become a query until you send it to the database and execute it.

And on top of that, you are vulnerable to sql injection attacks

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please explain how I have to solve this than?
execute those queries. you're already doing it with the insert ones, so I have no idea why you think you can just dump sql into a string and have results magically show up without ever calling ->exec() or ->query()
So I've added $conn->exec($sql); just under the line where I declare $sql, but it still doesn't work... I still have a lot to learn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.