2017-03-16 105 views
0

需要你的幫助。通過php pdo將數組的數據添加到數據庫時遇到了一些問題。我是業餘的前端開發人員。那離後端很遠,所以除了你之外沒有人能幫助我!在數據庫表中,我有一些列,其中包括「myActions」 - 需要將來自輸入的所有數據以名稱name =「action []」的形式逐行放入此列。 在HTML代碼中,我有輸入的名字那樣:如何將數組放入數據庫(php,pdo)?

<div id="field"> 
    <input autocomplete="off" class="input form-control" id="field1" name="action[]" type="text" placeholder="Type something" data-items="8"/> 
    <button id="b1" class="btn add-more" type="button">+</button> 
</div> 

在php文件:

<?php 
$incident_number = $_POST['incident_number']; 
$incident_type = $_POST['incident_type']; 
$incident_subject = $_POST['incident_subject']; 
$incident_time = $_POST['incident_time']; 
$status = $_POST['status']; 
$wasdone = $_POST['action']; 
try { 
/*** connect to SQLite database ***/ 
$dbh = new PDO("sqlite:myDB2"); 
/*** echo a message saying we have connected ***/ 
//echo 'Connected to database<br />'; 
/*** The SQL SELECT statement ***/ 
$Log = date(DATE_RFC2822)." Creation".PHP_EOL; 
//echo $Log; 
$sql = "INSERT INTO myData 
(incident_number,incident_type,incident_subject,incident_time,status) values 
(:incident_number,:incident_type,:incident_subject,:incident_time,:status);" 
$query = $dbh->prepare($sql); 
$query->bindParam(':incident_number', $incident_number); 
$query->bindParam(':incident_type', $incident_type); 
$query->bindParam(':incident_subject', $incident_subject); 
$query->bindParam(':incident_time', $incident_time); 
$query->bindParam(':status', $status); 

//$query->bindParam(':Log', $Log, PDO::PARAM_STR); 
$query->execute(); 
//$query->execute(array(':NameImp'=>$NameImp)); 
// Close file db connection 
$dbh = null; 
    } 

    catch(PDOException $e) 
{ 
echo $e->getMessage(); 
} 
try { 

/*** connect to SQLite database ***/ 
$dbh = new PDO("sqlite:myDB2"); 
/*** echo a message saying we have connected ***/ 
//echo 'Connected to database<br />'; 
/*** The SQL SELECT statement ***/ 
$Log = date(DATE_RFC2822)." Creation".PHP_EOL; 
//echo $Log; 
$sql = "INSERT INTO myActions (action) values (:wasdone);"; 
foreach ($wasdone as $key => &$value) { //pass $value as a reference to the array item 
$query->bindParam($key, $value); // bind the variable to the statement 
} 
//$query->bindParam(':Log', $Log, PDO::PARAM_STR); 
$query->execute(); 
//$query->execute(array(':NameImp'=>$NameImp)); 
// Close file db connection 
$dbh = null; 
    } 

    catch(PDOException $e) 
{ 
echo $e->getMessage(); 
} 
?> 

回答

0

你可以使用PHP的implode()功能,加入一個數組中的元素連接成一個字符串,由分隔一個自定義子字符串。

稍後,您可以使用explode()在從數據庫查詢時將字符串變回可工作的數組。

注:雖然這是一個快速的解決方案,可以爲您的使用情況下工作,如果數據集中的陣列變得過大或複雜項目的增加,你應該看看data normalization並附加表爲您actions陣列元素作爲良好的數據管理實踐。