我有一个表单,显示数据库中的选择ID,选择和定义配对。表单是动态的......根据用户的不同,可能会有任意数量的这些配对。以下是三个配对的示例:
选择ID,选择,定义
选择ID,选择,定义
选择ID,选择,定义
页面显示正常,但如果用户想要编辑选择或定义,则在提交表单时收到以下错误(注意:第41行是我的更新查询):
“注意:未定义的偏移:第41行(链接到我的php文件)第41行”
我认为通知告诉我查询不是在读取我的三个数组中的信息...但我不知道我应该在查询中添加什么以便它能正确读取。非常感谢你的帮助。
if(isset($_POST['submit'])){
$selection_id = array();
$selection = array();
$definition = array();
foreach ($_POST as $key => $value){
// If array variable starts with "pd_selection_id_for_" save to $selection_id array, otherwise continue to the next array.
if(strpos($key, 'pd_selection_id_for_') !== false){
$selection_id[] = mysql_real_escape_string($value);
}else if(strpos($key, 'selection_for_') !== false){
$selection[] = mysql_real_escape_string($value);
}else if(strpos($key, 'definition_for_') !== false){
$definition[] = mysql_real_escape_string($value);
}
}
// Count one of the arrays to select the paired fields and update the database.
$total = count($definition);
for ($i=1; $i <= $total; $i++){
// Update query for the paired selections and definitions.
$query = mysql_query("UPDATE `pd_selections` SET `pd_selection` = '$selection[$i]', `pd_definition` = '$definition[$i]' WHERE `pd_selection_id` = '$selection_id[$i]' ") or die(mysql_error());
}
}
答案 0 :(得分:0)
次要语法错误第41行的修复程序如下:
$query = mysql_query("UPDATE `pd_selections` SET `pd_selection` = '".$selection[$i]."', `pd_definition` = '".$definition[$i]."' WHERE `pd_selection_id` = '".$selection_id[$i]."'") or die(mysql_error());
答案 1 :(得分:0)
Undefined Offset
错误表示您尝试在阵列中访问的位置未设置,因此未定义。
问题是您的数组未在您尝试从循环访问的索引处初始化,请尝试以下操作:
$i = 0;
foreach ($_POST as $key => $value){
//initialize array at position $i
$selection_id[$i] = $selection[$i] = $definition[$i] = '';
if(strpos($key, 'pd_selection_id_for_') !== false){
$selection_id[$i] = mysql_real_escape_string($value);
}else if(strpos($key, 'selection_for_') !== false){
$selection[$i] = mysql_real_escape_string($value);
}else if(strpos($key, 'definition_for_') !== false){
$definition[$i] = mysql_real_escape_string($value);
}
$i++;
}
这样你知道你的所有数组大小都相同,因此将设置在其他数组设置的相同位置。