【问题标题】:Getting "ERROR: invalid input syntax for type double precision" in PostgreSQL在 PostgreSQL 中获取“错误:类型双精度的无效输入语法”
【发布时间】:2015-01-07 19:04:56
【问题描述】:

我使用这个脚本将数据插入我的数据库:

<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]:查询失败:错误:双精度类型的输入语法无效:

【问题讨论】:

  • 那么传递给pg_exec()的字符串$query的值是多少?
  • 我认为对于 double,您在查询中指定值时不需要添加引号 (")。

标签: php postgresql


【解决方案1】:

应避免手动引用,因为它容易出错并受到潜在的注入攻击。

大多数SQL 库都有一个函数,它接受参数,并在查询中使用占位符。该库负责引用,并防止注入点。

此代码的最佳方法可能是使用pg_query_params,它允许您将参数作为数组传递,并为您处理转义。您在查询中使用$1$2 等作为占位符。

所以基本上你的VALUES 子句将被($1, $2, $3...) 替换,以此类推,值被传递给pg_query_params 而不是直接插值。

【讨论】:

    【解决方案2】:

    结合@khampson 所说的,我认为您的核心问题是您引用了latitudelongitude 字段,我猜这不是字符串,而是精确的双精度数。但是您将它们解析为来自 PHP $_POST 的字符串,并像构建字符串一样构建 SQL 查询。

    所以你应该做两件事:

    1. 使用pg_query_params
    2. 当您构建要传递的值数组时 到pg_query_params 确保将这些值转换为浮点数。这个 以便pg_query_params 可以适当地了解 键入以便它知道 NOT 将其作为字符串引用但要处理 它是原始数字类型。

    微观例子:

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

    【讨论】:

    • 谢谢你的回答先生,
    • 谢谢你的回答,我终于可以解决这个问题了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多