doushi8187 2014-01-25 19:55
浏览 51
已采纳

mysql error.Error在sql查询的语法中

The code below is giving an error.The query alone is working fine on phpmyadmin directly but but in my php code:

Database Error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'to\',\' message\',\'from\')' at line.. but i cannot figure out why?

<?php
$con = mysqli_connect("localhost","","","");
if (!$con)
  {
     echo" Not connected to database";
  die('Could not connect: ' . mysqli_error());
  }
if(isset($_POST['submit'])){
$username=$_SESSION["username"];
$sql = "INSERT INTO `dbase.mail`(`Date`, `to`, `message`, `from`) VALUES (CURDATE(),\'$_POST[username1]\',\'$_POST[message]\',\'$username\')";
$xy=mysqli_query($con,$sql);
if (!$xy)
  {
  die('Database Error ' . mysqli_error($con));
  }
echo "Your message is stored";


} 
  • 写回答

1条回答 默认 最新

  • doukangbin9698 2014-01-25 20:03
    关注

    Several problems:

    • You must delimit the database name and table separately.

      INSERT INTO `dbase`.`mail` -- RIGHT
      

      not this:

      INSERT INTO `dbase.mail` -- WRONG
      
    • You don't need to backslash single-quotes inside a double-quoted string.

      $string = "that's the way"; -- RIGHT
      

      not this:

      $string = "that\'s the way"; -- WRONG
      
    • The error message suggests that you are using straight single-quotes to delimit your columns, not back-ticks.

      INSERT INTO `dbase`.`mail`(`Date`, `to`, `message`, `from`) -- RIGHT
      

      not this:

      INSERT INTO 'dbase.mail'('Date', 'to', 'message', 'from') -- WRONG
      
    • You must not interpolate $_POST variables directly into your SQL! This will allow hackers to attack your website easily. See What is SQL injection? and How can I prevent SQL injection in PHP?

      This is not the source of the error you asked about in this question, but it's a security practice you must learn how to handle properly before you put your code on the internet. If you were an electrician, this is analogous to safe wiring to prevent fires.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站