2017-08-05 140 views
1

下面的代码按预期工作。它将3个条目添加到表格'关键字'中。php的神秘行为

<?php 
include "config.php"; 
try{ 
    // $conn = new PDO(DBINFO,USER,PASS); 
    // $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)"; 
    // $stmt = $conn->prepare($sql); 
    // $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR); 
    // $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR); 
    // $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR); 
    // $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR); 
    // $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR); 
    // $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR); 
    // $stmt->execute(); 

    for($i=0; $i<3; $i++){ 
     $conn2 = new PDO(DBINFO,USER,PASS); 
     $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)"; 
     $stmt2 = $conn2->prepare($sql2); 
     $a = 'asdfds'; 
     $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR); 
     $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR); 
     $stmt2->execute(); 
    } 
} 
catch(PDOException $pe){ 
    die("Could not connect to the database :".$pe->getMessage()); 
} 
?> 

然而,当我运行下面的代码(在这里我注释掉第一部分),该项目得到补充6次的“关键字”表。

<?php 
include "config.php"; 
try{ 
    $conn = new PDO(DBINFO,USER,PASS); 
    $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)"; 
    $stmt = $conn->prepare($sql); 
    $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR); 
    $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR); 
    $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR); 
    $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR); 
    $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR); 
    $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR); 
    $stmt->execute(); 

    for($i=0; $i<3; $i++){ 
     $conn2 = new PDO(DBINFO,USER,PASS); 
     $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)"; 
     $stmt2 = $conn2->prepare($sql2); 
     $a = 'asdfds'; 
     $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR); 
     $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR); 
     $stmt2->execute(); 
    } 
} 
catch(PDOException $pe){ 
    die("Could not connect to the database :".$pe->getMessage()); 
} 
?> 

我不明白这一点。任何帮助?

+0

请使用bindValue而不是bindParam进行测试,并保留第三个/ type参数。 –

回答

2

为什么您首先创建4个到同一服务器和架构的不同连接?

循环创建连接并在覆盖语句和连接的引用时自动关闭连接。

但是,循环之前的原始连接将保持打开状态,并且可以重复使用该语句。如果在循环之前创建第三个连接而不关闭它,则最终会有9个条目。

因此,删除对连接对象的引用,如果它们不再需要(这包括关联的语句)。

或更好地重用连接,而不是为每个语句创建新连接。