简体   繁体   中英

MySQL PDO safely delete row in table?

If I understood this correctly, then this would be the way to safely replace a row in a table:

$stmt = $db->prepare("REPLACE INTO MyTable(ColA,ColB) VALUES(:ColA,:ColB)");
$stmt->execute(array(':ColA' => $colA, ':ColB' => $colB));
$affected_rows = $stmt->rowCount(); 

But how would I safely delete a row? (Only by knowing the ColA value)

You're doing it right by using PDO and prepared statements - this is the safe route to executing queries. The same logic can be used for a delete:

$stmt = $db->prepare("DELETE FROM MyTable WHERE ColA = :ColA");
$stmt->execute(array(':ColA' => $colA));

Prepared statements can (and should) be used for any type of query, whether SELECT , INSERT , REPLACE , DELETE , UPDATE , etc... The 'prepared' magic to it is the separation between the query itself and the values of the parameters you are using. :ColA is a placeholder that you will replace when executing the query - in this case by using the array with the placeholder name and the value to use in its place - array(':ColA'=>$colA) . This is the safe way to execute queries because it prevents parameters (user input) from being misinterpreted as SQL commands, and thus minimizing the risk of malicious queries being executed on your server.

In short, you're doing it right.

Use a prepared statement in exactly the same way as you have for the REPLACE query

$stmt = $db->prepare('DELETE FROM MyTable WHERE ColA = ?');
$stmt->execute([$colA]);

or, if you're really sold on named parameters...

$stmt = $db->prepare('DELETE FROM MyTable WHERE ColA = :ColA');
$stmt->execute([':ColA' => $colA]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM