php 验证后插入数据到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9809030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert data to database after validation
提问by NullPoiиteя
Im working in a php form where Im validating the feilds with regular expression. Validation working fine but I want to insert data into database after the validation finish with no error I dont know how to rite this ?
我在一个 php 表单中工作,我用正则表达式验证字段。验证工作正常,但我想在验证完成后将数据插入数据库而没有错误我不知道如何编写这个?
Im facing a prolem and data is inserting empty records into database each time I click submit. Also , I want after the insert is done to redirect to a Thank you page .
我面临一个问题,每次单击提交时,数据都会将空记录插入数据库。另外,我想在插入完成后重定向到一个谢谢页面。
I really appreciate your help and suggestion .
我非常感谢您的帮助和建议。
here is my code
这是我的代码
<?php
$errname = "";
$errage = "";
$errmobile = "";
if($_POST["ac"]=="login"){
// Full Name must be letters, dash and spaces only
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
$errname = '<p class="errText">Please enter your full name </p>';
// age must be 2 digits
if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
$errage = '<p class="errText">Age must be 2 digits</p>';
// Mobile mask 050-0000000
if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
$errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';
// contact to database
$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");
mysql_select_db("career_system");
//Get data in local variable
$v_name=$_POST['name'];
$v_age=$_POST['age'];
$v_gender=$_POST['gender'];
$v_mobile =$_POST['mobile'];
$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";
mysql_query($query) or die(mysql_error());
}
echo "Your information has been received";
}
?>
</head>
<body>
<div align="center">
<p> </p>
</div>
<form name="form1" action="<?php echo $PHP_SELF; ?>" method="POST">
<p>
<input type="hidden" name="ac" value="login">
</p>
<table width="485" border="0">
<tr>
<td width="48">Full Name</td>
<td width="150"><input name="name" type="text" id="name" value="<?php echo $_POST["name"]; ?>"></td>
<td width="273"><?php if(isset($errname)) echo $errname; ?></td>
</tr>
<tr>
<td>Age</td>
<td><input name="age" type="text" id="age" value="<?php echo $_POST["age"]; ?>"></td>
<td><?php if(isset($errage)) echo $errage; ?></td>
</tr>
<tr>
<td>Gender</td>
<td><input name="gender" type="radio" value="Male" checked>
Male
<input name="gender" type="radio" value="Female">
Female</td>
<td> </td>
</tr>
<tr>
<td>Mobile</td>
<td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
<td><?php if(isset($errmobile)) echo $errmobile; ?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input name="reset" type="reset" id="reset" value="Reset"></td>
<td> </td>
</tr>
</table>
</form>
回答by webbiedave
You can simply use an $errors
array and check for its emptiness before inserting:
您可以简单地使用$errors
数组并在插入之前检查其是否为空:
$errors = array();
if ($_POST["ac"]=="login") {
if (!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['name']))
$errors['name'] = '<p class="errText">Please enter your full name </p>';
if (!preg_match("/^\d{2}$/", $_POST['age']))
$errors['age'] = '<p class="errText">Age must be 2 digits</p>';
// etc...
if (!$errors) {
$query = "
insert into applicant
(name, age, gender, mobile )
values
(
'".mysql_real_escape_string($v_name)."',
'".mysql_real_escape_string($v_age)."',
'".mysql_real_escape_string($v_gender)."',
'".mysql_real_escape_string($v_mobile)."'
)
";
mysql_query($query);
}
// etc...
}
// Later in your HTML:
<tr>
<td>Mobile</td>
<td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
<td><?php if(isset($errors['mobile'])) echo $errors['mobile'] ?></td>
</tr>
Make sure to escape data before sending it to the database (hence, the mysql_real_escape_string
calls)! An important piece of advice would be to actually abandon the mysql_
functions as they are antiquated. You should use PDO instead. It's much easier, more efficient and eliminates much of the SQL injection threat with little effort:
确保在将数据发送到数据库之前转义数据(因此,mysql_real_escape_string
调用)!一个重要的建议是实际上放弃这些mysql_
功能,因为它们已经过时了。您应该改用 PDO。它更容易、更高效,并且毫不费力地消除了大部分 SQL 注入威胁:
try {
$dbh = new PDO("mysql:host=localhost;dbname=mydb", 'username', 'password');
} catch(PDOException $e) {
die('Could not connect to database!');
}
$stm = $dbh->prepare('INSERT INTO applicant (name, age, gender, mobile ) VALUES (?, ?, ?, ?)');
$stm->execute(array($v_name, $v_age, $v_gender, $v_mobile));
回答by max_
Add a space after applicant - INSERT INTO
applicant(name, age, gender, mobile )
在申请人 -INSERT INTO
申请人之后添加一个空格(name, age, gender, mobile )
Also, your code is insecure and your database is now vulnerable to attack. Make sure you escape all of your strings before you insert them into a db!
此外,您的代码不安全,您的数据库现在容易受到攻击。在将它们插入数据库之前,请确保将所有字符串转义!
回答by Araw
How about something like:
怎么样:
if($_POST["ac"]=="login"){
// Full Name must be letters, dash and spaces only
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
$errname = '<p class="errText">Please enter your full name </p>';
// age must be 2 digits
if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
$errage = '<p class="errText">Age must be 2 digits</p>';
// Mobile mask 050-0000000
if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
$errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';
// contact to database
$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");
mysql_select_db("career_system");
//Get data in local variable
$v_name=$_POST['name'];
$v_age=$_POST['age'];
$v_gender=$_POST['gender'];
$v_mobile =$_POST['mobile'];
if($errname != "" || $errage != "" || $errmobile != "")
echo "Error!";
else{
$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";
mysql_query($query) or die(mysql_error());
}
}
And just for your own safety, when storing posted values into a database, always check that they are not some type of attack (like for example SQL injection) by using:
为了您自己的安全,在将发布的值存储到数据库中时,请始终使用以下方法检查它们是否不是某种类型的攻击(例如 SQL 注入):
mysql_real_escape_string(param);