2017-08-05 58 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個條目。

因此,刪除對連接對象的引用,如果它們不再需要(這包括關聯的語句)。

或更好地重用連接,而不是爲每個語句創建新連接。