我有一个下拉列表,用户可以在其中选择类型,当用户单击下拉列表中的其他类型时,我必须显示一个完成的文本框。。
但现在我如何才能获得文本框的值并插入数据库。
这是我的脚本,当用户选择其他选项时,它会显示文本框。
<script type="text/javascript">
function CheckColors(val) {
var element = document.getElementById('others');
if (val == 'others') element.style.display = 'block';
else element.style.display = 'none';
}
</script>
<form name="f1" method="POST" action="">
<select name="type" onchange='CheckColors(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="others">others</option>
</select>
<input type="text" name="others" id="others" style='display:none' />
<input type="submit" name="submit" />
</form>
一切都很好。。除了从文本框中获取值。有人能帮我如何获取文本框值并插入数据库吗。。
您的html页面a.html
<script type="text/javascript">
function CheckColors(val) {
var element = document.getElementById('others');
if (val == 'others') element.style.display = 'block';
else element.style.display = 'none';
}
</script>
<form name="f1" method="POST" action="b.php"> <!--post data to b.php-->
<select name="type" onchange='CheckColors(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="others">others</option>
</select>
<input type="text" name="others" id="others" style='display:none' />
<input type="submit" name="submit" />
</form>
php页面b.php
<?php
if(isset($_POST['submit']))
{
$selectType=$_POST['type'];
$inputText=$_POST['others'];
$mysqli = new mysqli("localhost", "my_user", "my_password", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s'n", mysqli_connect_error());
exit();
}
$sql="insert into tablename (keyType,keyOther) values(?,?)";
/* create a prepared statement */
if ($stmt = $mysqli->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ds", $selectType,$inputText);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
}?>
您可以在php代码中使用if语句,如下所示:
<?php
if ($_POST['type'] == 'others') {
$type = $_POST['others'];
} else {
$type = $_POST['type'];
}
?>
然后,您可以像往常一样将$type插入数据库,显然要小心正确验证和转义数据。
您可以将值作为
firsrt check
if(isset($_POST["submit"]))
{
$other = $_POST["other"];
then fire your sql insert query by making connection to database.
}
else
{
echo "post ! set";
}
<?php
if(isset($_POST['submit']))
{
$others=$_POST['others'];
}
?>
我假设您正在将表单发布到另一个页面,并使用MySQL。
您的表单应该有action="page.php"
Page.php作为您提交到的页面。
以下是page.php可能是什么:
<?php
$con=mysqli_connect("ipAddress","my_user","my_password","my_db");
//your database connection
$other = $_POST['others'];
//The "others" is the name of the field your posting
mysqli_query($con,"INSERT INTO... fieldname = '$other'");
// your SQL query goes here.
?>
此外,您还希望防止SQL注入,这里有一个链接可以让您开始使用它。http://www.veracode.com/security/sql-injection
在将数据插入数据库之前,您需要确保验证、清理、检查错误等。如果有人试图攻击你的数据库,不这样做可能会导致严重的问题。
此外,您可能希望在另一个文件中设置数据库连接变量并将其包含在内,这样您的信息会更安全。