I am trying to add +1 to a row in my table and using the following code
try {
$query = $con->prepare( "UPDATE sitename SET hits = hits + 1
WHERE sitename = ?" );
$query->bindValue( 1, $url );
$query->execute();
// show error
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
I think the table is set up right for the field hits, the type is int(11)
As you can see I am trying to learn as I go, also I have read a few questions on here that give a similar answers to the same problem but adapted the code to work.... in this case not to work.
in the above code I bind the value sitename, do I need to do the same for hits?
the following code does nothing to the row at all,
the following question on stackoverflow has a very detailed error and this is where i got the base of this code from, like I said I have done some searching around before posting I just think I'm missing something or completely not understanding the problem.
This code does not echo an error too.
Two questions, two answers.
First, as @Fred points out, remove the comma after hits = hits + 1
and the UPDATE
statement will work.
Second,
in the above code I bind the value sitename, do I need to do the same for hits?
No. You use bind variables to pass data between the SQL code and the client code (in this case, your php code.) Updating the value of hits
is handled entirely within the SQL and is not passed in or out.
With PDO you can also use named bind variables, which would look like this:
$query = $con->prepare( "UPDATE sitename SET hits = hits + 1
WHERE sitename = :url" );
and then either
$query->bindParam(':url', $url);
$query->execute();
or simply
$query->execute(array(':url' => $url));
The above code has no error handling, as that was not the issue I was attempting to address. Error handling is important, but in this case I leave it as an exercise for the reader.