Boris Boris - 5 months ago 48
PHP Question

Increment value in a MySql query using PDO

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

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

$verPorTodos=$salerInfo2['phone'];
}


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:

$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$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

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. http://php.net/manual/en/pdo.prepare.php 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?