开发者

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.


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 :-)


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 . "'";


I find that concatenating queries causes me major headaches with syntax errors-- all those quotes and dots sprinked around like pepper. Here's how I would write the query:

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

Note that "name" is a reserved word and should not be used as a column name. Also if id is an integer, $catID doesn't need to be quoted.


You can try:

$update = "update table_name SET name = '$name', email = '$email', password = '$password', phoneno = '$phoneno' WHERE id = '$id'";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜