How do you use spatial data types with an example?

This content provides an overview of how to use spatial data types in MySQL, including a practical example for better understanding. Spatial data types are used to store, query, and manipulate geographical data, making them essential for location-based applications.

MySQL, Spatial Data Types, Geographical Data, Location-based Applications, GIS

        
        // Connect to MySQL database
        $mysqli = new mysqli("localhost", "user", "password", "database");

        // Check connection
        if ($mysqli->connect_error) {
            die("Connection failed: " . $mysqli->connect_error);
        }

        // Create a spatial table
        $createTableSQL = "CREATE TABLE places (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            location POINT NOT NULL,
            SPATIAL INDEX(location)
        ) ENGINE=InnoDB;";

        if ($mysqli->query($createTableSQL) === TRUE) {
            echo "Table 'places' created successfully.";
        } else {
            echo "Error creating table: " . $mysqli->error;
        }

        // Inserting spatial data
        $insertSQL = "INSERT INTO places (name, location) VALUES 
        ('Central Park', ST_Point(-73.9654, 40.7851)),
        ('Statue of Liberty', ST_Point(-74.0445, 40.6892));";

        if ($mysqli->query($insertSQL) === TRUE) {
            echo "New records created successfully.";
        } else {
            echo "Error: " . $insertSQL . "
" . $mysqli->error; } // Querying spatial data $querySQL = "SELECT name, ST_AsText(location) AS location FROM places;"; $result = $mysqli->query($querySQL); if ($result->num_rows > 0) { // Output data of each row while($row = $result->fetch_assoc()) { echo "Name: " . $row["name"]. " - Location: " . $row["location"]. "
"; } } else { echo "0 results"; } // Close connection $mysqli->close();

MySQL Spatial Data Types Geographical Data Location-based Applications GIS