在PHP中获取变量导致数据库不被接受

时间:2015-06-06 18:36:02

标签: php mysql

所以我有这个PHP代码:

session_start();
$servername = "localhost";
$username = "root";
$dbname = "3890ask3_db";


$con = mysql_connect($servername, $username, "", $dbname)
  or die("Failed to connect to MySQL: " . mysql_error());

  $db=mysql_select_db($dbname,$con) 
  or die("Failed to connect to MySQL: " . mysql_error());  

  $query = mysql_query("SELECT * FROM register where Username = '$_SESSION[Username]'") or die(mysql_error()); 
   $row = mysql_fetch_array($query) or die(mysql_error());

    if(isset($_GET['selecttoy']))
    {
   $clname=$row['Name'];
   $clsurname=$row['Surname'];
   $clemail=$row['Email'];
   $stoy=$_GET['selecttoy'];


   $query2 = "INSERT INTO order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
  if (mysql_query($query2)) {
    echo "Order created successfully!";
} else {
    echo "Error: "  . "<br>" . mysql_error($con);
 }
}

?>

php页面实际上可以读取get变量,但是当我尝试在数据库中插入某些内容时,我收到此错误消息:

&#34;您的SQL语法出错了;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便使用附近的订单(ClName,ClSurname,ClEmail,ToyCode,OrderID)VALUES(&#39; mar&#39;,&#39; kyr&# 39;,&#39; dgg&#39;在第1行&#34;

我尝试了一切但没有结果......有人可以帮助我吗? 提前谢谢....

1 个答案:

答案 0 :(得分:0)

您无法直接使用order,因为它是保留字。尝试将其括在(``)中。如下所示: -

$query2 = "INSERT INTO `order` (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;

注意: - 始终尝试添加sql error reporting code

停止使用mysql_*,使用mysqli_*PDO

您的上述代码已针对SQL Injection打开。感谢。