Boris Boris - 1 year ago 172
PHP Question

Increment value in a MySql query using PDO

Why this code is not working (the value of $artInfo2['phoneState'] is 1):

$bdd->prepare("UPDATE `articulos` SET `telVisto` = `telVisto` + 1 WHERE `ID` ='".$_GET['id']."' ");


I'm using a PDO conection that works good because it works good with other queries. Here is my data base conection that I use on te top of my page:

$bdd = new PDO('mysql:host=localhost;dbname=lacajota', 'root', '', $pdo_options);

And yes I want to update telVisto incrementing 1 for each time the code is run.

Thank you

Answer Source

Step 1: Sanitize your input. Never concatenate a query with $_GET['something'], because I can delete your whole database like that.
Step 2: Handle errors properly.
Step 3: prepare() doesn't execute the query. It returns a Prepared Statement. You still need to execute it.

$stmt = $bdd->prepare("UPDATE `articulos` SET `telVisto` = `telVisto` + 1 WHERE `ID` =:id ");
$stmt->execute(array(':id' => $_GET['id']));

Step 4. If nothing works, can you check if you even have a row to update? Does the query

SELECT * FROM `articulos` WHERE `ID` = (insert your ID here manually)

return anything? Maybe the problem is that you don't work with the correct data?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download