Php 在每个页面上插入空数据重新加载
我在将数据发布到DB时遇到问题。当我重新加载页面或访问网站时,它会将空数据发送到DB。这是因为我没有为此使用按钮(嗯,我指的是onclick事件)。直接在表单下编写php代码,如果您填充文本和textarea等空格并单击按钮,它就会工作。不过,我是php新手,所以我真正需要的是,学习如何使用PHP向数据库中插入数据的按钮,以防止在每次加载表单时插入数据 这是密码Php 在每个页面上插入空数据重新加载,php,Php,我在将数据发布到DB时遇到问题。当我重新加载页面或访问网站时,它会将空数据发送到DB。这是因为我没有为此使用按钮(嗯,我指的是onclick事件)。直接在表单下编写php代码,如果您填充文本和textarea等空格并单击按钮,它就会工作。不过,我是php新手,所以我真正需要的是,学习如何使用PHP向数据库中插入数据的按钮,以防止在每次加载表单时插入数据 这是密码 <?php $host="localhost"; $user="root"; $
<?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!!"
?>
1)使用而不是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");
}
?>
使用表单的action属性。例如action=“index.php?action=form”
因为isset($\u POST)&!如果你正在处理更大的webapp,空($\u 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..
}
}
你能给我一个@Anant为什么#1无效的原因吗?因为两者都一样好,都有自己的能力。在问我之前,让我知道你为什么写第一行。您需要给出一些示例You's right@Anant我应该写一个示例,但使用PDO可以让您的生活更轻松,因为它简单、面向对象且外观令人愉悦。Koray我也给出了建议和答案,请检查所有答案,并对其中一个进行评分和投票,其中一个对您有效,并且也将是描述性的。