0

我一直找不到任何明确回答这个问题的东西,并且一直想知道。对不起,如果这是一个新手问题。

在以下情况下,我是否必须增加或更改我的 PDO 变量。如果我有两个这样的查询:

$stmt     = $dbh->prepare('
    INSERT INTO messages 
        (content) 
    VALUES 
        (:content)
        ');
$stmt->bindValue('content', $content);
$stmt->execute();
$msg_id  = $dbh->lastInsertId();

......

$stmt1     = $dbh->prepare('
    INSERT INTO something else 
        (stuff) 
    VALUES 
        (:stuff)
        ');
$stmt1->bindValue('stuff', $stuff);
$stmt1->execute();
$var_id  = $dbh->lastInsertId();

如果我在两者上都使用 $stmt,而在第二个上使用 $stmt 被认为是不好的做法,或者一旦我有了 $msg_id,我可以重用 $stmt 吗?作为 PDO 的新手,重复变量会很方便,但我不想引入以后需要修复的错误。

4

2 回答 2

2

从技术上讲,一旦您完成了第一个查询的 $stmt 工作,您就可以将该 PHP 变量重用于另一个语句/查询:没有什么可以阻止您这样做。


尽管如此,我还是喜欢有两个具有明确名称的变量的想法——这意味着比$stmtand更具信息性$stmt1

For example, if you have two PHP variables named $stmtSaveMessage and $stmtSaveUser, each time one of these variables is used, you will immediately know what the code does : you will not have to think if $stmt right now points to the statement that saves a message, or if it's been overridden to point to the statement that saves something else.


By itself, $stmt generally indicates that you are working with a statement, that does something database-related ; but using a more significant variable name will immediately make your code easier to read, easier to understand, and easier to maintain -- and, when programming, we tend to spend more time maintaining old code than writing new one...

于 2012-05-18T16:45:36.053 回答
1

我认为重用相同的变量是个好主意。它不那么混乱并节省了一点内存。

真的,这完全取决于您,但我个人认为为每个查询创建一个新的资源句柄是一种不好的做法,除非有特定的原因要挂在旧的资源句柄上。

于 2012-05-18T16:31:47.610 回答