PHP从数组创建查询,可以';t在foreach语句中选择两个索引
我试图从传递ID和详细信息字段的表单创建查询,post数组如下所示:PHP从数组创建查询,可以';t在foreach语句中选择两个索引,php,arrays,Php,Arrays,我试图从传递ID和详细信息字段的表单创建查询,post数组如下所示: array(2) { ["ID"]=> array(9) { [0]=> string(3) "10a" [1]=> string(3) "10b" [2]=> string(3) "10c" [3]=> string(3) "10d" [4]=> string(3) "10e" [5]=> string(3) "
array(2) {
["ID"]=> array(9)
{
[0]=> string(3) "10a"
[1]=> string(3) "10b"
[2]=> string(3) "10c"
[3]=> string(3) "10d"
[4]=> string(3) "10e"
[5]=> string(3) "10f"
}
["Details"]=> array(9)
{
[0]=> string(19) "This is textfield 1"
[1]=> string(17) "This is textfield 2"
[2]=> string(0) ""
[3]=> string(0) ""
[4]=> string(0) ""
[5]=> string(0) ""
}
}
ID硬编码到页面中并始终传递,用户可以根据需要填写详细信息
if ($_POST['OthProb']['Details'] != '') {
// Catch issue text and assign to variable
foreach ( $_POST['OthProb']['Details'] as $key => $value) {
$id = $_POST['OthProb']['ID']->$key;
$dets = $value;
// Focus on fields with values and join the array values together in a query string
if ($dets != ''){
$string = "INSERT into $table (AccountID, OtherID, ID, Details) VALUES ($_POST[AccountID], $_POST[OtherID], '".$id.", '".$dets."')";
$sql = $DBH->prepare($string);
// $sql->execute();
// var_dump ($id);
}
}
}
创建以下内容
"INSERT into tbl_problems (AccountID, OtherID, ID, Details) VALUES (80, 80, '10f, 'This is Title issue')"
“细节”输出正确,但它在ID中一直循环到最后一个,这是因为我嵌套了foreach吗?构建循环的最佳方式是什么?尝试替换此行:
$id = $_POST['OthProb']['ID']->$key;
借
作为旁注,您可能希望在此行中添加一个额外的单引号(就在
$id.“
):$string=“INSERT into$table(AccountID,OtherID,id,Details)值($\u POST[AccountID],$\u POST[OtherID],“$id.”,“$dets.”);
变为$string=“INSERT into$table(AccountID,OtherID,id,id,Details)值($\u POST[AccountID]、$\u POST[OtherID]、“$id.”、“$dets.”);
太棒了,我发誓我昨天试过了,我一定是在别处出错了!不管怎样都很有效,非常感谢。
$id = $_POST['OthProb']['ID'][$key];