Form in PHP to update MySQL Update PDO - exec?

1

I have to use this code, I do not have another option, I do not find how to make the assignment in the UPDATE receiving the input data

$id = $_POST["id"];
$nombre = $_POST["nombre"];
$categoria = $_POST["categoria"];
$precio = $_POST["precio"];

$sql = "UPDATE 'revistas' SET 'nombre'= ".$nombre." , 'categoria' = ".$categoria.", 'precio' =". $precio." WHERE 'id' =". $id;
$affectedrows = $db->exec($sql);
if(isset($affectedrows)) {
    echo "Record has been successfully updated";
}

ORIGINAL CODE

$sql = "UPDATE 'vehiculo' SET 'modelo'= 'Gol' , 'modelo' = '2018'  ,'kilometros' = '10' WHERE 'id' = 2" ;
$affectedrows = $db->exec($sql);
if(isset($affectedrows)) {
    echo "Record has been successfully updated";
}
    
asked by Leonel 12.06.2018 в 05:14
source

1 answer

2

It is necessary to write a secure code, which can not be with exec , since there is data that you do not control and that a malicious user can modify to inject you malicious code. exec could agree in the case of queries that must be executed directly in a secure way ... this is not the case here.

The query you want, would surely have to:

  • use prepared queries, changing values by markers ?
  • create an array with the values that come in the POST
  • pass those values in the form of an array in execute (it can be done differently if you prefer, using bindParam )
  • to know the affected rows use rowCount

This would be the code:

$id = $_POST["id"];
$nombre = $_POST["nombre"];
$categoria = $_POST["categoria"];
$precio = $_POST["precio"];

$sql = "UPDATE 'revistas' SET 'nombre' = ? , 'categoria' = ?, 'precio' = ? WHERE 'id' = ?";
$arrParams=array($nombre,$categoria,$precio,$id);
$stmt=$db->prepare($sql);
$stmt->execute($arrParams);

$affectedrows = $stmt->rowCount();
if($affectedrows > 0) {
    echo "Record has been successfully updated";
}
    
answered by 12.06.2018 в 06:02