以下表格收集有关访客颜色偏好的数据。
如果用户提交空白表单,如何将预定义的替代值插入到mysql数据库中。
这里要考虑的是我不想阻止用户使用表单验证提交空白表单。
我目前的后端代码如下:
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO users (color_name) VALUES (%s)",
GetSQLValueString($_POST['color_name'], "text")),
mysql_select_db($database_x, $x);
$Result1 = mysql_query($insertSQL, $x) or die(mysql_error());
$insertGoTo = "choicecolor.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
<table align="center">
<tr valign="baseline">
<td align="right" nowrap="nowrap">Enter Color Name:</td>
<td><input type="text" name="color_name" value="" size="32" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><input type="hidden" name="MM_insert" value="form1" /></td>
<td>
<input type="submit" value="Submit Color Name" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</form>
如果访问者在未输入任何值的情况下提交空白表单,则应将预定义值(例如"no choice"
)插入数据库,如果访问者提交带有输入值"yellow"
的填充表单,值"yellow"
,应插入数据库。
如何在这种情况下使用PHP预定义值?
答案 0 :(得分:0)
在php中执行此操作添加类似这样的内容
$toInsert = isset($_POST['color_name'])? $_POST['color_name']: 'Your default string';
然后改变这一行
$insertSQL = sprintf("INSERT INTO users (color_name) VALUES (%s)", GetSQLValueString($_POST['color_name'], "text"));
到这个
$insertSQL = sprintf("INSERT INTO users (color_name) VALUES (%s)", GetSQLValueString($toInsert, "text"));
但你应该首先看看PDO等。另外,正如 Dark Wish 所提到的那样,在数据库级别而不是php上执行此操作可能会更好。