PHP要插入数据库错误

时间:2013-06-07 05:32:42

标签: php mysql

所以,我正在尝试调试我的程序,这是一个用于插入数据库的简单PHP代码。

每当我在浏览器中运行它时:

http://localhost:3456/maps/savemdata.php?descr=Best&lat=-37.12345&lng=122.12345

它应该将值插入数据库,但我得到的是:

  

查询无效:您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以获得正确的语法   在'desc,lat,lng)附近使用VALUES('Best',' - 37.12345','122.12345')'   在第1行

Savemdata.php

<?php
$hostname = '127.0.0.1:3306';        
$dbname   = 'login'; // Your database name.
$username = 'root';             // Your database username.
$password = '';                 // Your database password. If your database has no password, leave it empty.

mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
mysql_select_db($dbname) or DIE('Database name is not available!');

// Gets data from URL parameters
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];


// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
         " (desc, lat, lng ) " .
         " VALUES ('%s', '%s', '%s' );",
         mysql_real_escape_string($desc),
         mysql_real_escape_string($lat),
         mysql_real_escape_string($lng));

$result = mysql_query($query);

if (!$result) {
  die('Invalid query: ' . mysql_error());
}

?>

3 个答案:

答案 0 :(得分:4)

DESC是mysql中的关键字。你应该把它拿回来;)

答案 1 :(得分:3)

desc是保留关键字,恰好是列的名称。要避免语法错误,您需要使用反引号来转义它。例如,

$query = sprintf("INSERT INTO `markers` " .
     " (`desc`, `lat`, `lng` ) " .
     " VALUES ('%s', '%s', '%s' );",
     mysql_real_escape_string($desc),
     mysql_real_escape_string($lat),
     mysql_real_escape_string($lng));

如果您有权更改表,请将列名更改为不是保留关键字,以避免再次出现问题。

答案 2 :(得分:0)

Rahul,我建议你使用PDO。尝试按以下方式更改代码。

<?php
$hostname = '127.0.0.1:3306';        
$dbname   = 'login'; // Your database name.
$username = 'root';             // Your database username.
$password = ''; 

// database connection
$conn = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);

// new data
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];

// query
$sql = "INSERT INTO markers  (desc,lat,lng) VALUES (:desc,:lat,:lng)";
$q = $conn->prepare($sql);
$q->execute(array(':desc'=>$desc,
                  ':lat'=>$lat,
                  ':lng'=>$lng));


?>