PHP MySQL POINT 字段的数据类型

PHP Data Type For MySQL POINT Field

我创建了一个 MySQL table,其中字段的类型为 POINT,用于存储经纬度坐标(例如:36.6294654 -93.1725982)。

我在提交表单时遇到错误,我假设这是由于数据类型不匹配造成的。

SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field

我的理解是POINT应该有示例的格式(我也试过纬度,经度)。我认为问题在于 space 将变量转换为 STRING.

我是不是漏掉了什么?

这是我的 PHP 连接到数据库并插入记录的代码。

// use google's geocoding service to transform an address into lat/lon coordinates (https://developers.google.com/maps/documentation/geocoding/)
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($street) . ',+' . urlencode($city) . ',+' . urlencode($state) . ',+' . urlencode($zip) . '&key=YOUR_API_KEY');
$json = json_decode($json, true);
$latlon = $json['results'][0]['geometry']['location']['lat'] . ' ' . $json['results'][0]['geometry']['location']['lng'];
try {
    $dbh = new PDO('mysql:host=someserver;port=someport;dbname=somedatabase', 'someusername', 'somepassword', array(PDO::ATTR_PERSISTENT => true));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = 'INSERT INTO Venues (Name, Street, City, State, Zip, Country, TimeZone, LatLon, Phone, Email, Website, Host, Notes) VALUES (:name, :street, :city, :state, :zip, :country, :timezone, :latlon, :phone, :email, :website, :host, :notes)';
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(":name" => $name, ":street" => $street, ":city" => $city, ":state" => $state, ":zip" => $zip, ":country" => $country, ":timezone" => $timezone, ":latlon" => $latlon, ":phone" => $phone, ":email" => $email, ":website" => $website, ":host" => $host, ":notes" => $notes));
    if ($stmt->rowCount() == 1) {
        echo '<p>"' . $name . '" creation succeeded.</p>';
    } else {
        echo '<p>"' . $name . '" creation failed.</p>';
    }
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $dbh = null;
}
catch(PDOException $e) {
    echo $e->getMessage();
}

或者,我可以只使用单独的纬度和经度字段,但我想练习使用 msyql 的内置几何功能。

编辑...

听从 this answer 的建议,我用 POINT() 包围了 $latlon。不过,它并没有改变结果。

编辑 2...

这是 table 结构,以防万一看起来不正确。

VenueKey    int(11)
Name        varchar(255)
Street      varchar(255)
City        varchar(255)
State       varchar(2)
Zip         varchar(10)
Country     varchar(2)
TimeZone    varchar(20)
LatLon      point
Phone       varchar(20)
Email       varchar(255)
Website     varchar(255)
Host        varchar(255)
Notes       text

这应该可以解决您的问题:

$latlng = 'POINT(' . $json['results'][0]['geometry']['location']['lat']. " " . $json['results'][0]['geometry']['location']['lng']. ')';

然后用 PointFromText:

包装你的 :latlon
$sql = 'INSERT INTO Venues (Name, Street, City, State, Zip, Country, TimeZone, LatLon, Phone, Email, Website, Host, Notes) VALUES (:name, :street, :city, :state, :zip, :country, :timezone, PointFromText(:latlon), :phone, :email, :website, :host, :notes)';