Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to write PHP SQL Update Statement

I have this PHP SQL statement:

$updateCategory = "UPDATE category 
                   SET name=".$name.", description=".$description.",
                       parent=".$parent.", active=".$active." 
                   WHERE id=".$catID."";

What is the best way to write this?

Thanks,

Chris.

like image 349
Chris Avatar asked Aug 30 '26 13:08

Chris


2 Answers

I suggest you use prepared statements instead of concatenating the query string together:

$sql = 'UPDATE 
           category
        SET
           name=:name,
           description=:description,
           parent=:parent, 
           active=:active
        WHERE
           id=:catID';

if you are using PDO, which I strongly suggest, you would then call it like this:

$params = array(
    ':name'        => $name,
    ':description' => $description,
    ':parent'      => $parent,
    ':active'      => $active,
    ':catID'       => $catID
);

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

You might ask, "why all this hassle?" The advantages of this approach are quite overwhelming:

  • You don't have to care about SQL injection, since the database driver now handles the correct transformation of the input parameters
  • You don't have to care about escaping special characters, but you can concentrate on what you want to achieve rather than on how to achieve it :-)
like image 155
Dan Soap Avatar answered Sep 01 '26 03:09

Dan Soap


You could format it like this to make it more readable.

$updateCategory = "
    UPDATE
        category
    SET
        `name` = '" . $name . "',
        `description` = '" . $description . "',
        `parent` = '" . $parent . "',
        `active` = '" . $active . "'
    WHERE
        `id` = '" . $catID . "'";
like image 42
Michiel Pater Avatar answered Sep 01 '26 03:09

Michiel Pater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!