Jan Beck
Jan Beck

Reputation: 13

How to read geometry data type from MySQL database using PHP

I have a table in MySQL that stores polygons. I can read this back on the command line using the following query:

mysql> SELECT polygonid, AsText(thepolygon) FROM polygons;
+-----------+----------------------------------------------------------------------------------------------------------------+ | polygonid | AsText(thepolygon) |
+-----------+----------------------------------------------------------------------------------------------------------------+ | 1 | POLYGON((36.96318 127.002881,37.96318 127.002881,37.96318
128.002881,36.96318 128.002881,36.96318 127.002881)) | +-----------+----------------------------------------------------------------------------------------------------------------+ 1 row in set, 1 warning (0.02 sec)

When I try to read this in PHP using the same query, polygonid comes back correctly, but thepolygon comes back as empty:

$query = "SELECT polygonid, AsText(thepolygon) FROM polygons";
$result = mysqli_query($con, $query);

while ($row = mysqli_fetch_array($result)) {
    var_dump($row['polygonid']);
    var_dump($row['thepolygon']);

    [...]

results in

string(1) "1" NULL

meaning that 'thepolygon' comes back as NULL, but the 'polygonid' comes back just fine.

If I change the query to

SELECT polygonid, thepolygon FROM polygons

then I do get back binary data:

string(1) "1" string(97)
"�t{I{B@�1�3/�_@�t{I�B@�1�3/�_@�t{I�B@��`@�t{I{B@��`@�t{I{B@�1�3/�_@"
string

It's almost as if astext() does not work. What am I doing wrong?

Thanks for any input at all!

Upvotes: 1

Views: 2059

Answers (1)

BadHorsie
BadHorsie

Reputation: 14544

Looks like it might just be because you've not given the AsText() selection an alias which can be picked up from the PHP array.

If you print out $row you might be able to see that your array does not have a thepolygon key.

Have you tried this?

$query = "SELECT polygonid, AsText(thepolygon) AS thepolygon FROM polygons";

It works on the command line because you're just printing out whatever is selected in the query, but in PHP you're trying to print out array keys - i.e. the name of the fields selected. Your MySQL query does not select a field called thepolygon, so it doesn't exist in the array either.

Upvotes: 2

Related Questions