我的表单有多个下拉列表(16)speed[]
和其他一些字段
下拉框中的数据必须插入到Mysql表中
我做的是我取了计数count($_POST["speed"]);
然后循环直到速度数组结束。
问题是:
如果未选择任何下拉菜单,则返回“-1”,如果使用`($ _POST [“speed”] [$ i]!=“ - 1”),但不能比较并进入IF循环
插入查询无效,不确定如何附加额外commas
$ sql
INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ('name', '', ''-1''800''-1''-1''200''-1''-1''-1''-1''-1''-1''-1''-1''-1''-1''200'', '208')
我的PHP代码
$itemCount = count($_POST["speed"]);
$itemValues=0;
$query = "INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ";
$bldSpltString="";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(($_POST["speed"][$i]!="-1") || !empty($_POST["speed"][$i])) {
$bldSpltString .= "'" . $_POST["speed"][$i] ."'";
}
}
$queryValue .= "('" . $wkout . "', '" . $wtype . "', '" . $bldSpltString . "', '" .$_SESSION['id']."')";
$sql = $query.$queryValue;
echo $sql;
exit;
答案 0 :(得分:3)
我会做这样的事情:
<?php
function dynamicInsert($table_name, $assoc_array){
$keys = array();
$values = array();
foreach($assoc_array as $key => $value){
$keys[] = $key;
$values[] = $value;
}
$query = "INSERT INTO `$table_name`(`".implode("`,`", $keys)."`) VALUES('".implode("','", $values)."')";
echo $query;
}
dynamicInsert("users", array(
"username" => "Test User",
"password" => "Password123"
));
?>
警告:此代码不安全,我会对发送到mysql的变量运行mysql_real_escape_string和任何其他必要的卫生设施。我还避免允许这个脚本在任何公共场合运行,因为动态插入可能会带来巨大的安全风险!