这是对我上一个问题的跟进。我试图访问多维数组的数据,以便插入到数据库中。我一直在寻找论坛以及我自己尝试不同的东西,但无法找到任何有用的东西。这是数组的样子:
$_POST[] = array[stake](
'stakeholder1' => array(
'partner'=> 'partner',
'meet'=> 'meet'
),
'stakeholder2' => array(
'partner'=> 'partner',
'agreement'=> 'agreement',
'train'=> 'train',
'meet'=> 'meet'
),
);
我正在尝试做(UPDATE list WHERE stakeholder = "stakeholder1" SET partner =1, meet =1
)这样的事情,具体取决于选择了哪个利益相关者/选择(四种不同的选项)。谢谢,
答案 0 :(得分:1)
这一个将为选中的选项设置1,为未选中的选项设置为0(否则您将错过一些数据更新)。
$optionsList = array('partner', 'agreement', 'train', 'meet');
$stakeHolders = array('stakeholder1', 'stakeholder2', ...);
foreach($stakeHolders as $stakeHolder)
{
$selectedOptions = $_POST[$stakeHolder];
$arInsert = array();
foreach($optionsList as $option)
$arInsert[] = '`'.$option.'` = '.intval(isset($selectedOptions[$option]));
$sql = "UPDATE list
SET ".implode(", ", $arInsert)."
WHERE stakeholder = '".mysql_real_escape_string($stakeHolder)."'";
// TODO: execute $sql (mysql_query(), or PDO call,
// or any wrapper you use for DB)
}
答案 1 :(得分:0)
$query = '';
foreach ($_POST as $k => $v) {
$query .= "UPDATE list WHERE stakeholder = '$k' SET " . implode(" = 1," $v) . ",";
}
$query = substr($query, 0, -2); //Get rid of the final comma
如果我正确理解您的数据库架构,这应该可以为您提供所需的内容。
答案 2 :(得分:0)
如果您使用的是PDO,可以执行以下操作:
foreach($_POST as $stakeholder => $data) {
$sth = $dbh->prepare('UPDATE `list` SET `' . implode('` = 1, `', array_keys($data)) . '` = 1 WHERE stakeholder = ?');
$sth->execute(array($stakeholder));
}
务必清理用户输入(数据键......)。
答案 3 :(得分:-1)
foreach($main_array as $key => $sub_array) {
$sql = 'UPDATE list
WHERE stakeholder = "{$key}"
SET ';
$sets = array();
foreach($sub_array as $column_value)
$sets[] = $column_value." = 1";
$sql = $sql.implode(',', $sets);
}