4

DETAILS

I'd like to make use of mysql's spatial extension, so I am trying to store longitude and latitude in a mysql table of datatype POINT using bindParam. Unfortunately, I keep getting the error SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'location' cannot be null.

I've checked that longitude and latitude have values. So the problem has to be with my code, but I cannot see what I am doing wrong.

Here is the code I am using.

$location=$latitude." ".$longitude;
$sql = "INSERT INTO my_geodata SET location = PointFromText('POINT(:location)')";
      //INSERT INTO my_geodata SET location = PointFromText('POINT(-41 12)');    

try 
{
    $stmt = $dbh->prepare($sql);            
    $stmt->bindParam(':location', $location, PDO::PARAM_STR);           
    $stmt->execute();   
    $dbh = null;
}

catch(PDOException $e)
{               
    echo $error=$e->getMessage();
}

QUESTION

What am I doing wrong? How can I insert longitude and latitude into a mysql table (that uses POINT datatype) with PDO and bindParam?

VARIATION

Based on AgreeOrNot's answer, a slightly different way to achieve this is

$location = 'POINT(' . $latitude . " " . $longitude . ')';    
$sql = "INSERT INTO my_geodata (location) VALUES (PointFromText(:location))";
6
  • Does the insert work with the comment out code? Commented Jul 27, 2013 at 2:35
  • Yes the insert works. Commented Jul 27, 2013 at 2:37
  • Have you tried using a prepared statement instead with ? instead of :? Commented Jul 27, 2013 at 2:37
  • No I haven't done that. What is the difference?binding values instead of parameters? Commented Jul 27, 2013 at 2:41
  • Ya, worth a shot if only to eliminate, it'll take a moment to test. Insert bla into bla where bla = ? sql->bindValue(1, coords); Commented Jul 27, 2013 at 2:45

2 Answers 2

7

Note that parameterizing queries is not (simple) string replacement. In your code your query parameter is put in a string literal which will be kept untouched.

Try this:

$location = 'POINT(' . $latitude . " " . $longitude . ')';
$sql = "INSERT INTO my_geodata SET location = PointFromText(:location)";
Sign up to request clarification or add additional context in comments.

2 Comments

It's worth noting that putting PointFromText() in the variable IS NOT the same as putting it in the query.
PointFromText( has been updated to ST_PointFromText(
1

Spatial extensions aren't designed for latitude and longitude yet, they are designed for Cartesian coordinates. The distance functions don't take into account the curvature of the earth so always give wrong results. Quite sad I know...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.