将记录添加到表PHP / MySQL

时间:2013-09-22 17:47:40

标签: php mysql

所以这应该是PHP / MySQL表的一个非常简单的添加 - 但由于某种原因我无法开始工作。我试过玩引号放置,连接等。但是我想我需要一些帮助。谢谢

<?php 
//Variables from Form
$Fs = "$_POST[Fs]";
$Ls = "$_POST[Ls]";
$T = "$_POST[T]"; 
$A = "$_POST[A]";
$Sn = "$_POST[Sn]";
?>

<h2>Add</h2>
<form  id="form"  action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<input name="Fs" type="text" value="First Name" size="20" maxlength="60" onfocus="if (this.value=='First Name') this.value='';"onblur="if (this.value=='') this.value='First Name';"/>
<input name="Ls" type="text" value="Last Name" size="20" maxlength="60"onfocus="if (this.value=='Last Name') this.value='';"onblur="if (this.value=='') this.value='Last Name';" />
<input name="T" type="text" value="Telephone" size="20" maxlength="60" onfocus="if (this.value=='Telephone') this.value='';"onblur="if (this.value=='') this.value='Telephone';"/>
<input name="A" type="text" value="Address" size="20" maxlength="60"onfocus="if (this.value=='Address') this.value='';" onblur="if (this.value=='') this.value='Address';"/>
<input name="Sn" type="text" value="Student Number" size="40" maxlength="40" onfocus="if (this.value=='Student Number') this.value='';" onblur="if (this.value=='') this.value='Student Number';"/>

 <?php 
if(isset($_POST['Submit'])) 
 { 

//Conections

 $con = mysql_connect("localhost", "root", "root") or die("Error connecting to database: ".mysql_error());
mysql_select_db("assign2") or die(mysql_error());

//Insert Statements

if($Fs != null && $Ls != null && $T != null && $T != null && $A != null && $Sn != null) {
    echo "<br><br><br>" .  $Fs . " " . $Ls . " " . $T . " " . $A . " " . $Sn ;
     mysqli_query($con, "INSERT INTO 'assign2table' (First_Name , Last_Name , Telephone , Address ,Student_Number) VALUES ('$Fs' , '$Ls' . '$T' . '$A' . '$Sn')");
 }
else {
echo "Missing Info"; 

  }
 }
 ?>

2 个答案:

答案 0 :(得分:0)

您在插入查询中使用了(DOT)(。)而不是逗号(,)。

mysqli_query($ con,“INSERT INTO'assign2table'(First_Name,Last_Name,Telephone,Address,Student_Number)VALUES('$ Fs','$ Ls','$ T','$ A','$ Sn “)“);

答案 1 :(得分:0)

首先,每次调用数据库函数时,都应检查其返回值以查看它是否失败。当你不这样做时,某些事情可能会失败,你不会知道发生了什么。

这就是这种情况:你已经用insert而不是逗号分隔了insert语句中的一些值。这是一个SQL语法错误。查询应如下所示:

$result = mysqli_query($con, "INSERT INTO 'assign2table' (First_Name , Last_Name , Telephone , Address ,Student_Number) VALUES ('$Fs' , '$Ls', '$T', '$A', '$Sn')");
if ($result === FALSE) {
    echo "Insert failed: ".mysqli_error($con);
}

其次,此代码具有明显的SQL注入漏洞。您应该学会使用prepared statements