Skip to the content.

Creating an API

<?php

require_once('db.php');

$stmt = $conn->prepare("SELECT city FROM referendum GROUP BY city ORDER BY city");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//echo '<pre>'; print_r($rows);

$arr = array();

foreach($rows as $row) {
  $arr["cities"][] = $row["city"];
}

if(count($rows) == 0){
  $arr["error"] = "City Not Found";
}else{
  $arr["error"] = "";
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
<?php

require_once('db.php');

$city = $_POST['city'];

$stmt = $conn->prepare("SELECT city , town FROM referendum WHERE city = :city ");
$stmt->bindParam(':city', $city);   // güvenlik için bind ederek kullanıyoruz !!!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//echo '<pre>'; print_r($rows);

$arr = array();

foreach($rows as $row) {
  $arr["towns"][] = $row["town"];
}

if(count($rows) == 0){
  $arr["error"] = "City Not Found";
}else{
  $arr["error"] = "";
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);