PDO准备好的语句-参数名称中的冒号用于什么? [英] PDO prepared statement - what are colons in parameter names used for?

查看:70
本文介绍了PDO准备好的语句-参数名称中的冒号用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用PDO时,我已经看到很多文章在命名参数前面使用冒号(:),还有一些不使用冒号的文章.我会尽快不使用冒号,只是因为它的击键次数少了一点,而且更易于阅读.

I've seen many articles using colons (:) in front of named parameters when using PDO, and a couple that do not use the colon. I'd just as soon not use the colon, simply because it's one less keystroke and slightly easier to read.

这似乎对我来说很好,但是我很好奇在使用冒号时是否缺少一些重要的东西?

It seems to be working fine for me, but I'm curious if there is something important that I'm missing when it comes to the use of colons?

例如,这很好用:

function insertRecord ($conn, $column1, $comumn2) {
    try {
        $insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
        VALUES(:column1, :column2)');
        $insertRecord->execute(array(
                'column1' => $column1,
                'column2' => $column2
            ));
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

与大多数使用它的开发人员相反,它也可以工作:

As opposed to most developers using this, which also works:

function insertRecord ($conn, $column1, $comumn2) {
    try {
        $insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
        VALUES(:column1, :column2)');
        $insertRecord->execute(array(
                ':column1' => $column1,
                ':column2' => $column2
            ));
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

execute语句参数中注意冒号.

Notice the colons in the execute statement parameters.

我想了解冒号的用途.

推荐答案

SQL语句中必须使用冒号,以指示哪些标识符是占位符.

Colons are required in the SQL statement, to indicate which identifiers are placeholders.

冒号是可选的.文档中对它们进行了指定,但是实现足够聪明,可以弄清楚如果不使用它们,您的意思是什么(您还有什么意思?).

Colons in the execute() or bindParam() calls are optional. The documentation specifies them, but the implementation is clever enough to figure out what you mean if you leave them out (what else could you mean?).

这篇关于PDO准备好的语句-参数名称中的冒号用于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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