2017-03-02 52 views
0

比方說,我對用戶,表單和所有者ID具有價值。用戶的值保持不變,但ownerID可能會隨時變化。用於插入多個值的BindParam

例如:

$user = "Farhana"; // fix value 
$form = "Registration"; // fix value 
$ownerID = array("23","50","33"); // item in array not fix, may have many ownerID 

然後我想用這樣一個SQL語句插入多個值。

INSERT INTO messages (user,ownerID,form) VALUES ("Farhana","23","Registration"),("Farhana","50","Registration"),("Farhana","33","Registration"); 

所以我出來了foreach解決方案,但我不確定這是否正確或不。

// prepare 
$stmt = $this->conn->prepare("INSERT INTO messages (user,ownerID,form) VALUES (?,?,?)"); 
// bind param 
foreach ($ownerID as $ID){ 
    $stmt->bind_param("sss",$user,$ID,$form); 
    $stmt->execute(); 
} 

回答

0

這並不重要,但只是爲了清楚起見,bind_param只能被調用一次。

$stmt = $this->conn->prepare("INSERT INTO messages (user,ownerID,form) VALUES (?,?,?)"); 
$stmt->bind_param("sss",$user,$ID,$form); 
foreach ($ownerID as $ID){ 
    $stmt->execute(); 
}