Search code examples
phpmysqlpolygonspatialwkt

Using PHP pack() to Convert WKT into WKB


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 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


Solution

  • 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.