How to insert point data into mysql using PDO bindParam?
DETAILS
I would like to use mysql spatial extension, so I am trying to store longitude and latitude in a mysql table of POINT datatype using bindParam. Unfortunately I keep getting SQLSTATE error [23000]: Integrity constraint violation: 1048 The "location" column cannot be null.
I have verified that longitude and latitude are relevant. So the problem must be with my code, but I can't 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 to insert longitude and latitude into mysql table (which uses POINT datatype) with PDO and bindParam?
OPTION
Building on the answer from AgreeOrNot, a slightly different way to achieve this is
$location = 'POINT(' . $latitude . " " . $longitude . ')';
$sql = "INSERT INTO my_geodata (location) VALUES (PointFromText(:location))";
source to share
Note that query parameterization is not a (simple) string replacement. In your code, the query parameter is placed in a string literal that will remain intact.
Try the following:
$location = 'POINT(' . $latitude . " " . $longitude . ')';
$sql = "INSERT INTO my_geodata SET location = PointFromText(:location)";
source to share