Fetching by x and y

Viewed 33

I am playing around with my little game and I have grid map in there and I store data for every of grid tile in database. It's 100x100 map and database stores 10 000 records. For every field of map. It's like terrain type, units on field etc.

I am downloading this data to game and load into map. But the thing is I can't fetch it properly.

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $conn->prepare("SELECT * FROM mmo ORDER BY id ASC");
  $stmt->execute();

  // set the resulting array to associative

    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $r[] = $result;
    }

    for ($i = 0; $i <= 2500; $i++) {
        echo "[type".$i."]";
        echo $r[$i]['type'];
        echo "[type".$i."]";
        echo "[unit".$i."]";
        echo $r[$i]['unit'];
        echo "[unit".$i."]";

        
        echo "<br>";
    }
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>

This is the code I am using. For now, I don't even use x and y and I am using id instead. As you see I am loading 2500 fields.

Basically, I need help with fetching and sending data from MySQL database of fields only I see on screen. Like only those that in database have values that fits this: x>100 & x<300 & y>100 & y < 300

1 Answers

Use WHERE to restricts to the fitting values, and a more useful ORDER BY criteria.

SELECT * 
FROM mmo 
WHERE x BETWEEN 101 AND 299 AND y BETWEEN 101 AND 299
ORDER BY y ASC, x ASC

This will return the information ordered by row and then ordered by column within rows.

Related