通过php插入SQL错误

时间:2015-03-17 10:05:38

标签: php mysql

当我尝试通过php编码在sql表中插入值时,我收到一条错误消息。即使我也重新创建了一个新的数据库,但它无法正常工作。所以我需要你的帮助来解决它。我的错误信息如下:

  

插入失败!您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册   要使用的语法   邻近'用法,有效期,价格)的值(' indranil'' SOM'' WWBIPL_NE_4GB'' 512kbps的'&# 39; 4GB'&#39 3'   在第1行

我的html代码如下:

<html>
<head>
<body>
<form action="insert.php" method="post">
<select name="package">
<option value="WWBIPL_NE_4GB">WWBIPL_NE_4GB</option>
<option value="WWBIPL_NE_6GB">WWBIPL_NE_6GB</option>
</select>
Firstname:<input type="text" name="firstname">
Lastname:<input type="text" name="secondname">
Email:<input type="text" name="email">
Address:<input type="text" name="address">
<input type="submit">
</form>
</body>
</head>
</html>

这是我的PHP代码

<?php
$fstname=$_POST["firstname"];
$sndname=$_POST["secondname"];
$price=$_POST["package"];
if($price=="WWBIPL_NE_4GB")
{
$bandwidth="512kbps";
$usage="4GB";
$validity="30days";
$price1="499";
}
else if($price=="WWBIPL_NE_6GB")
{
$bandwidth="512kbps";
$usage="6GB";
$validity="90days";
$price1="1280";
}
$servername="localhost";
$username="root";
$password="";
$dbname="stock";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("Connection Failed".mysqli_error($conn));
}   $sql="insertintoisuue(Firstname,Lastname,Package,Bandwidth,Usage,Validity,Price)values('$fstname','$sndname','$price','$bandwidth','$usage','$validity','$price1')";
if(mysqli_query($conn,$sql))
{
echo"Data inserted successfully";
}
else
{
echo"Insertion failed".mysqli_error($conn);
}
mysqli_close($conn);
?>

2 个答案:

答案 0 :(得分:3)

Usage是mysql中的reserved word。你需要用反引号来逃避它,或者更好地重命名你的专栏

$sql="insert into isuue(Firstname,Lastname,Package,Bandwidth,`Usage`,Validity,Price)values('$fstname','$sndname','$price','$bandwidth','$usage','$validity','$price1')";

你应该使用准备好的陈述和原因,因为X.L.Ant提到你应该用空格写insert into ...

答案 1 :(得分:0)

替换:

$sql="insertintoisuue(Firstname,Lastname,Package,Bandwidth,Usage,Validity,Price)values('$fstname','$sndname','$price','$bandwidth','$usage','$validity','$price1')";

使用:

$sql="INSERT INTO isuue (Firstname, Lastname, Package, Bandwidth, Usage,
          Validity, Price ) 
      VALUES ('$fstname', '$sndname',' $price','$bandwidth',  
          $usage','$validity','$price1')";