开发者

Using PHP pack() to Convert WKT into WKB

开发者 https://www.devze.com 2023-04-10 15:44 出处:网络
I\'m using prepared statements to insert data into my database, problem is I\'m not able to use INSERT INTO table (polygon) VALUES (GeomFromText(POLYGON((?,?,?,?,?,?))))

I'm using prepared statements to insert data into my database, problem is I'm not able to use

INSERT INTO table (polygon) VALUES (GeomFromText(POLYGON((?,?,?,?,?,?))))

why? well, seems the GeomFromText itself is interpreted as text :/ so I figured I'd开发者_C百科 try pushing pure WKB strings into the db instead, problem is I can't really figure out how to pack a WKT into WKB.

Could someone help me do this with this format description: http://dev.mysql.com/doc/refman/5.0/en/gis-wkb-format.html and the doc for pack() over at: http://php.net/manual/en/function.pack.php


I see two problems. First, the GeomFromText function takes a string, so it should look like GeomFromText('POLYGON((0, 1, 2))') (note the quotation marks). Second, since the POLYGON... text is a string literal, it should be replaced with the wildcard, not the individual pieces. Your query should look like this:

INSERT INTO areas (name, polygon)
VALUES (?, GeomFromText(?))

You would then build the POLYGON((?, ?, ?, ?, ?, ?)) string in the application, not in the statement. Since PHP has safe string handling I would recommend using sprintf('POLYGON((%d, %d, %d, %d, %d, %d))', $var1, $var2, $var3, $var4, $var5, $var6) (sprintf is dangerous in C).

Alternatively, you can use MySQL's spatial functions to generate the points. I think this is what you were trying to do, but you don't pass them through GeomFromText. To build a polygon with MySQL's spatial functions, the documentation suggests you would need to do:

INSERT INTO areas (name, polygon)
VALUES (?, Polygon(LineString(Point(?, ?), Point(?, ?), Point(?, ?))))

Prior to MySQL 5.1.35 you would need to do:

INSERT INTO areas (name, polygon)
VALUES (?, GeomFromWKB(Polygon(LineString(Point(?, ?), Point(?, ?), Point(?, ?)))))


This is pretty straightforward. Grab a specification and use "C" for bytes, "V" for uint32's and "d" for doubles in your pack format strings. However, my advice is not to do that. First, rewriting a build-in function is a waste of time. Second, transferring binary data with sql is error prone (think of encoding issues for example). And third, according to http://dev.mysql.com/doc/refman/5.0/en/creating-spatial-values.html you don't even need GeomFromText, because mysql already treats unquoted wkt as binary.

0

精彩评论

暂无评论...
验证码 换一张
取 消