我有关于将数据发布到DB的问题。当我重新加载页面或转到网站时,它会向DB.Its发送空数据,因为我没有运行按钮(好吧,我的意思是onclick事件)为此。直接在表单下编写了一个php代码,如果你填写文本和textarea等空格并点击按钮就可以工作。虽然我是PHP的新手,所以我真正需要的是,学习如何运行一个按钮来使用PHP将数据插入数据库,以防止在每个表单加载时插入数据。
这是代码
<?php
$host="localhost";
$user="root";
$password="";
$db="mkappform";
$con=mysqli_connect("$host","$user","$password","$db");
if (! $con) die ("Unable to connect to database");
$name=$_POST["name"];
$nick=$_POST["nick"];
$pvnick=$_POST["pvnick"];
$age=$_POST["age"];
$country=$_POST["country"];
$timezone=$_POST["timezone"];
$servers=$_POST["servers"];
$checkban=$_POST["checkban"];
$contact=$_POST["contact"];
$history=$_POST["history"];
$reasons=$_POST["reasons"];
$whypastclans=$_POST["whypastclans"];
$anyotherinfo=$_POST["anyotherinfo"];
$query=mysqli_query($con,
"INSERT INTO mkappform(name,nick,pvnick,age,country,timezone,servers,checkban,contact,history,reasons,whypastclans,anyotherinfo)
values('$name','$nick','$pvnick','$age','$country','$timezone','$servers','$checkban','$contact','$history','$reasons','$whypastclans','$anyotherinfo')");
if($query == true)
echo "Application was sent successfully!!"
?>
答案 0 :(得分:1)
1)使用PDO statements代替 mysqli 它更好更简单。
2)使用'$name'
将等于'$name'
,因为使用单引号会按原样使用字符串,而是使用双引号这个"$name"
。
3)这是一个使用之前的音符:
的示例<?php
$host="localhost";
$user="root";
$password="";
$db="mkappform";
try {
$pdo = new PDO("mysql:host=$host;dbname=$db","$user","$password");
$name=$_POST["name"];
$nick=$_POST["nick"];
$pvnick=$_POST["pvnick"];
$age=$_POST["age"];
$country=$_POST["country"];
$timezone=$_POST["timezone"];
$servers=$_POST["servers"];
$checkban=$_POST["checkban"];
$contact=$_POST["contact"];
$history=$_POST["history"];
$reasons=$_POST["reasons"];
$whypastclans=$_POST["whypastclans"];
$anyotherinfo=$_POST["anyotherinfo"];
$insert_status = $pdo->query("INSERT INTO mkappform(name,nick,pvnick,age,country,timezone,servers,checkban,contact,history,reasons,whypastclans,anyotherinfo)
values('$name','$nick','$pvnick','$age','$country','$timezone','$servers','$checkban','$contact','$history','$reasons','$whypastclans','$anyotherinfo')");
if($insert_status){
echo "Application was sent successfully!!"
}else{
echo "an error occured when inserting data";
}
} catch (PDOException $e) {
echo $e->getMessage();
die("Unable to connect to database");
}
?>
实际上,我们在插入数据库时使用参数绑定来避免SQL注入
答案 1 :(得分:0)
使用表单的操作属性。例如action =&#34; index.php?action = form&#34;
因为如果你正在处理更大的webapp,isset($_POST) && !empty($_POST)
大部分时间都不够。
if(isset($_GET["action"]
{
//Open database
switch($_GET["action"])
{
case "form":
//callYourForm
form();
break;
case "anotherThing":
anotherThing();
break;
//can do more things if needed..
}
}