【发布时间】:2014-04-14 04:55:49
【问题描述】:
我想验证用户输入到 mysql 数据库的数据。 因此,用户不能在需要数字的字段中输入字母。 并在验证后将数据输入数据库。 我已经编写了该代码,但它不起作用.. 它接受数字字段的字母
<?php
include 'testinput.php';
error_reporting(E_ERROR | E_PARSE);
if(isset($_POST['submitted'])){
$con = mysqli_connect("localhost","USERNAME","PASSWORD","DATABASE");
if(mysqli_connect_errno()){
echo "Failed to connect";
}
$card1 = test_input($_POST['card']);
$first1= $_POST['first'];
$last1= $_POST['last'];
$id1 = test_input($_POST['id']);
$mob1 = test_input($_POST['mobile']);
$vis1 = test_input($_POST['visit']);
$query = "INSERT INTO aftness1_clients.clients (card, first, last, id, mobile, visit) VALUES ('$card1','$first1','$last1','$id1', '$mob1','$vis1')";
if(!mysqli_query($con, $query)){
echo "Error ". mysqli_error($con);
echo "<br>";
}
$newrecord ="<b>One client added Successfully !</b>";
}// end of main if
?>
<html>
<header>
<title>
Add a Client
</title>
</header>
<body bgcolor="#F0FFFF">
<br/> <br/> <center><font size="5" color="#4EE2EC"> Clients Information </font> </center> <br/>
<b>All fields are required:</b> <br/> <br/>
<form action = "insert.php" method="post">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New Client</legend>
<lable><font size="3" color="#38ACEC"><b>Card Number:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="card"/><br/>
<lable><font size="3" color="#38ACEC"><b>First Name:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="first"/><br/>
<lable><font size="3" color="#38ACEC"><b>Last Name:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="last"/><br/>
<lable><font size="3" color="#38ACEC"><b>ID Number:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="id"/><br/>
<lable><font size="3" color="#38ACEC"><b>Mobile Number:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="mobile"/><br/>
<lable><font size="3" color="#38ACEC"><b>Visits:</b></font></lable>
<input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="visit"/><br/>
</fieldset>
</br>
<font color="#FFFFFF"> <input type ="Submit" name="submit" value = "Add" align="right"/></font>
</form>
<?php
error_reporting(E_ERROR | E_PARSE);
echo $newrecord
?>
</body>
</html>
<br/><br/><br/>
<a href="index.php">Main Page</a>
这是 testinput 函数
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
我的代码哪里出了问题,还有其他方法可以检查数据的有效性吗?
【问题讨论】:
-
您在哪里进行验证?您需要使用正则表达式或 is_int() 来验证数值
-
请不要在随机输入时使用
stripslashes()。它只会破坏它!
标签: php mysql validation