Php 如何根据HTML表单中定义的变量动态生成MYSQL UPDATE语句
我正在使用一个相当长的HTML表单来更新与产品相关的许多细节——为简洁起见,我不会完整地共享该表单。然而,为了便于说明,这里有一个片段: HTML表单Php 如何根据HTML表单中定义的变量动态生成MYSQL UPDATE语句,php,html,mysql,forms,Php,Html,Mysql,Forms,我正在使用一个相当长的HTML表单来更新与产品相关的许多细节——为简洁起见,我不会完整地共享该表单。然而,为了便于说明,这里有一个片段: HTML表单 <form name="form1" method="post" action="update_ac.php"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <td> <inpu
<form name="form1" method="post" action="update_ac.php">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<input name="season" type="text" class="button_select" id="season" value="<?=$rows['season']; ?>" size="10" />
<input name="restock" type="checkbox" id="restock" value="on" <?php if($rows['restock']=='on') { echo 'checked="checked"'; } ?>/>
// other fields
</td>
</tr>
</table>
</form>
我不想在UPDATE语句中声明可能需要更新的每个字段。我希望UPDATE语句只处理相关字段,因为表单中存在已定义的PHP变量
目前,我收到了大量的通知:未定义变量x
,其中在发布表单时存在空字段
我希望这是有道理的——有点啰嗦
有什么建议吗?谢谢
更新
根据@Styphon的回答,我对其进行了轻微的修改,在查询的末尾添加了WHERE
条件
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
if( ! empty($val)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$product_id = $_POST['product_id'];
$query = $query . "WHERE product_id = '".$product_id."' ";
假设表中的所有字段名与表单输入的名称相同,这是直接的。您可以使用以下选项:
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
if( ! empty($val)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$sql = mysql_query($query);
为了更安全,您应该创建一个接受参数的白名单,即表中的列,如下所示:
$query = "UPDATE product SET";
$comma = " ";
$whitelist = array(
'title',
'rating',
'season',
'brand_id',
'cateogry',
// ...etc
);
foreach($_POST as $key => $val) {
if( ! empty($val) && in_array($key, $whitelist)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$sql = mysql_query($query);
这样,您的查询只能包含您设置的参数,如果有人设法注入额外的内容(例如通过更改表单输入的名称),它将不会被传递到您的数据库
我还建议您停止使用Mysql,因为它是免费的。你应该考虑或作为替代方案。看看
isset
也许>@Fluffeh-这并不能解决我的问题,因为我必须根据isset测试所有可能的变量。我试图避免声明超过50个变量。@我在real_escape_字符串中添加了nalply,现在也习惯于使用准备好的语句了。@Styphon-我刚刚意识到,语句末尾缺少WHERE product_id=$product_id
行。我已经更新了上面的代码。Thanks@nalply我在查询中使用了单引号,因此这是不相关的,该查询受到了保护。在你发表评论之前,你看到我的更新答案了吗?这不容易受到SQL注入的攻击吗?@arviman它有mysql\u real\u escape\u string
可以防止大多数注入尝试,但它不如使用准备好的语句好。
$query = "UPDATE product SET";
$comma = " ";
$whitelist = array(
'title',
'rating',
'season',
'brand_id',
'cateogry',
// ...etc
);
foreach($_POST as $key => $val) {
if( ! empty($val) && in_array($key, $whitelist)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$sql = mysql_query($query);