【问题标题】:How to put an array to DB (php, pdo)?如何将数组放入数据库(php,pdo)?
【发布时间】:2017-08-07 10:20:07
【问题描述】:

需要你的帮助。通过 php pdo 将数组的数据放入数据库时​​遇到了一些问题。我是业余前端开发人员。那离后端很远,所以除了你没有人来帮助我!在数据库表中,我有一些列,其中包括“myActions” - 需要将我输入中名称为 name="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 html database sqlite pdo


    【解决方案1】:

    您可以使用 PHP 的 implode() 函数将数组元素连接成单个字符串,并由自定义子字符串分隔。

    当您从数据库中查询字符串时,您可以稍后使用explode() 将字符串转换回可用的数组。

    注意:虽然这是一个适用于您的用例的快速解决方案,但如果数据集中的数组变得太大或您的项目变得复杂,您应该查看 data normalization 并为actions 数组元素作为良好的数据管理实践。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-10
      • 2018-08-01
      • 2014-12-06
      • 1970-01-01
      • 2012-03-28
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多