[英]PHP Data Type For MySQL POINT Field
我創建了一個MySQL表,其中的字段為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
應該具有示例的格式(我也嘗試過lat,lon)。 我認為問題在於空格將變量轉換為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的內置幾何功能。
編輯...
按照這個答案的建議,我用POINT()
包圍了$latlon
。 不過,它並沒有改變結果。
編輯2 ...
這是表結構,以防萬一看起來不正確。
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
PointFromText
:
$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)';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.