我使用此脚本将数据插入我的数据库:
<html>
<body>
<?php
include('koneksi.php');
$gid = pg_escape_string ($_POST['gid']);
$nama = pg_escape_string ($_POST['nama']);
$alamat = pg_escape_string ($_POST['alamat']);
$no_telfon = pg_escape_string ($_POST['no_telfon']);
$email = pg_escape_string ($_POST['email']);
$website = pg_escape_string ($_POST['website']);
$longitude = pg_escape_string ($_POST['longitude']);
$latitude = pg_escape_string ($_POST['latitude']);
$query = "INSERT INTO perguruantinggi( gid, nama, alamat, no_telfon, email, website, longitude, latitude )
VALUES ('" . $gid . "', '" . $nama . "', '" . $alamat . "', '" . $no_telfon . "', '" . $email . "', '" . $website . "', '" . $longitude . "', '" . $latitude . "')";
$result = pg_exec($query);
//$query = "INSERT INTO perguruantinggi (username, password, fullname, email, agama, no_hp)
//VALUES ('" . $username . "', '" . $password . "', '" . $email . "', '" . $fullname . "', '" . $agama . "', '" . $no_hp . "')" ;
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
?>
</body>
我在编译此脚本时发现了此错误。我对坐标数据类型使用双精度。
警告:pg_exec() [function.pg-exec]:查询失败:错误:双精度类型的输入语法无效:
应避免手动引用,因为它既容易出错,又容易受到潜在的注入攻击。
大多数 SQL 库都有一个函数,该函数接受参数,并在查询中使用占位符。库负责引用,并防止注入点。
对于此代码,最佳方法可能是使用 pg_query_params
,它允许您将参数作为数组传递,并负责为您转义。在查询中使用 $1
、 $2
等作为占位符。
因此,基本上您的VALUES
子句将被替换为($1, $2, $3...)
等等,并将值传递给pg_query_params
而不是直接插值。
结合
@khampson所说的,我认为你的核心问题是你引用了你的latitude
和longitude
字段,我猜这不是字符串,而是精确的双精度。但是你把它们解析为 PHP $_POST
中的字符串,并像构建字符串一样构建你的 SQL 查询。
所以你应该做两件事:
- 使用
pg_query_params
- 当您构建要传递的值数组时以
pg_query_params
确保将这些值强制转换为浮点型。这是为了让pg_query_params
可以对类型,以便它知道不要将其作为字符串引用,而是将它作为原始数字类型。
微例:
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$params = array(floatval($latitude), floatval($longitude));
$query = "INSERT INTO table (latitude, longitude) VALUES ($1, $2)";
pg_query_params($connection, $query, params);