如何将阵列放到DB(PHP,PDO)



需要您的帮助。将数组的数据通过PHP PDO放置到DB时遇到了一些问题。我是业余的Frond-End Dev。这离后端很远,所以除了您帮助我之外,没有人!在DB表中,我有一些列,以及其他" Myactions" - 需要将所有数据带有名称=" Action []"的输入中的所有数据。在html代码中,我有这样的输入名称:

<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();
}   
?> 

您可以使用PHP的implode()函数,该功能将数组的元素连接到单个字符串中,由自定义子字符串界定。

从数据库查询时,您可以稍后使用explode()将字符串变成可行的数组。

注意:虽然这是一个快速解决方案,可以适用于您的用例actions数组元素作为良好的数据管理实践。

最新更新