PHP / MySQL插入表单

时间:2015-06-07 09:19:06

标签: php mysql

一旦你进入网页,它进入SQL表,即使你没有提交,在你进入网页后立即向SQL表发送一个空白,这里是HTML表格和PHP表单。

<form name="" method="POST" action="">
<input class="" type="text" name="a1" id="a1" class="placeholder" placeholder="Enter the FRATERNITY Name">
<input class="" type="text" name="a2" id="a2" class="placeholder" placeholder="Enter YOUR Name">
<style>

<?php

$host="";
$username="";
$password="";
$database_name="";
$table_name="";

mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$database_name")or die("cannot select DB");

$a1=$_POST['a1'];
$a2=$_POST['a2'];

$sql="INSERT INTO $table_name(groupname, founder)VALUES('$a1', '$a2')";
$result=mysql_query($sql);

if($result){
echo "Group $a1 Has Been Created";

}

else {
echo "ERROR";
}
?> 

<?php 
// close connection 
mysql_close();
?>

1 个答案:

答案 0 :(得分:2)

如果是发布请求,您需要检查它,然后只执行您的代码。见下文:

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $host="";
    $username="";
    $password="";
    $database_name="";
    $table_name="";

    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$database_name")or die("cannot select DB");

    $a1=mysql_real_escape_string($_POST['a1']);
    $a2=mysql_real_escape_string($_POST['a2']);

    $sql="INSERT INTO $table_name(groupname, founder)VALUES('$a1', '$a2')";
    $result=mysql_query($sql);

    if($result){
    echo "Group $a1 Has Been Created";

    }

    else {
    echo "ERROR";
    }
    ?> 

    <?php 
    // close connection 
    mysql_close();
}

请注意,您的代码很容易受到SQL注入攻击。我没有弄清楚两个输入字符串以防止这种情况发生。