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.

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

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线