我正在尝试创建一个 HTML 表单,通过 php 将所有输入的值插入到 MySQL 数据库中。 对于本例,用户输入产品编号和供应商。
供应商应该由单选按钮和一个附加的“其他”文本字段来定义,用户可以在其中指定另一个选项... 当用户选择“其他”选项时,输入的值将正确插入 MySQL 数据库中,但是当选择其中一个单选按钮时,插入的不是供应商,而是文本“on”。 .. 我不明白为什么脚本会这样做,因为我在脚本中的任何地方都没有值“on”。
我已经搜索了谷歌和 stackoverflow,并尝试了很多方法,但我仍然无法让它工作。我是 php 和 html 新手,所以请对我宽容点。
下面是代码的精简版本。 (实际上,脚本还提交表单中的更多字段、 session 用户名和时间戳。)
有人知道“on”可能来自哪里以及如何解决这个问题吗?谢谢。
php部分代码:
<?php
if (isset($_POST['submit'])) {
// These set your initial variables. q1_* is for the queried entries in the form
$q2_productname = $_POST['q2_productname'];
$q3_supplier = $_POST['q3_supplier'];
if ($q3_supplier =='other'){
$q3_supplier = $_POST['q3_supplier_other'];
}
if (isset($q2_productname)) {
$q2_productname = trim($q2_productname);
$q2_productname = strip_tags($q2_productname);
$q2_productname = stripslashes($q2_productname);
$q2_productname = htmlspecialchars($q2_productname);
}
if (isset($q3_supplier)) {
$q3_supplier = trim($q3_supplier);
$q3_supplier = strip_tags($q3_supplier);
$q3_supplier = stripslashes($q3_supplier);
$q3_supplier = htmlspecialchars($q3_supplier);
}
$dbc = @mysql_connect (DBHOST, DBUSER, DBPASS) or die('Failure: ' . mysql_error() );
mysql_select_db(DBNAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO orders VALUES ('$q2_productname','$q3_supplier')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
}
然后是html/echo/script部分代码:
<?php
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thank you. Your product has been added to the order list!</p>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<div>
<label for="q2">Full product name:</label><br />
<textarea id="q2" name="q2_productname" rows="1" cols="50"></textarea>
</div>
</fieldset><br /><br />
<fieldset>
<div>
<label for="q3">Supplier (e.g. Sigma-Aldrich, VWR, ...):</label><br />
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" checked="checked" />Sigma-Aldrich
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" />VWR
<input type="radio" name="q3_supplier" id="q3" onchange="enableTxt()" />Other:
<input type="text" name="q3_supplier_other" id="other" disabled="disabled" />
<script>
function disableTxt() {
document.getElementById("other").disabled = true;
}
function enableTxt() {
document.getElementById("other").disabled = false;
}
</script>
</div>
</fieldset><br /><br />
</form>
最佳答案
设置 radio 输入的值属性。该值将发布到您的服务器。除非您指定,否则该值将为“on”。
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" checked="checked" value='Sigma-Aldrich'/>Sigma-Aldrich
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" value='VWR' />VWR
<input type="radio" name="q3_supplier" id="q3" onchange="enableTxt()" value='Other' />Other:
关于php - 在我的带有单选按钮和 'other' 文本字段的 HTML 表单中,单选按钮的值无法理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28354622/