0

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

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

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

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

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

保存数据.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());
}

?>
4

3 回答 3

4

DESC 是 mysql 中的一个关键字。你应该把它放在反引号里;)

于 2013-06-07T05:36:06.860 回答
3

desc is a reserved keyword and happens to be the name of your column. To avoid syntax error, you need to escape it using backtick. eg,

$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));

If you have the privilege to alter the table, change the column name to which is not a reserved keyword to avoid problem from occurring again.

于 2013-06-07T05:38:24.047 回答
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));


?>
于 2013-06-07T05:52:01.827 回答