DagelijksGamer
DagelijksGamer

Reputation: 21

How to update an sql db

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();
}

Upvotes: 1

Views: 51

Answers (1)

Marc B
Marc B

Reputation: 360572

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

Upvotes: 1

Related Questions