编写 PHP SQL 更新语句的最佳方法 [英] Best way to write PHP SQL Update Statement

查看:59
本文介绍了编写 PHP SQL 更新语句的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 PHP SQL 语句:

I have this PHP SQL statement:

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

最好的写法是什么?

谢谢,

克里斯.

推荐答案

我建议你使用prepared statements而不是将查询字符串连接在一起:

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

如果您使用的是 PDO,我强烈建议您这样做:p>

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:

  • 您不必关心 SQL 注入,因为数据库驱动程序现在可以处理输入参数的正确转换
  • 您不必关心转义特殊字符,但您可以专注于您想要实现的目标,而不是如何实现它:-)

这篇关于编写 PHP SQL 更新语句的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆