PHP JSON To Array Fetch Country Cities

PHP JSON To Array means how to use PHP with JSON, In this article we will fetch records from MySQL database and will return JSON array.

What is JSON?

JSON stands for javascript object notation, It's used for data exchanging between server and web browser and it's a lightweight data exchange formate

Explanation:

Ajax is the efficient way to communicate with a database, In this article, You will learn "PHP JSON To Array". In simple word, you will learn how to use JSON with PHP and how to fetch records from MySQL database and after how to return data in JSON format, we will return JSON array and you will learn how to show records from JSON array.  so let's create database and tables.
ajax fetch cities


database file
CREATE DATABASE country_db;


  CREATE TABLE `country` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `country_name` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1





CREATE TABLE `cities` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `country_id` int(11) NOT NULL,
 `city` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=latin1
style.css
body {
 margin: 0;
 padding: 0;
 font-family: sans-serif;
}

.container {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
}

.box {
 width: 500px;
 height: auto;
}

.group {
 margin: 10px 0px;
}

.control {
 width: 100%;
 height: 40px;
 border-radius: 5px;
 border:1px solid silver;
}

.result {
 border:1px dotted silver;
 padding: 10px;
 display: none;
}
db.php
<?php 

$db = new PDO("mysql:host=localhost;dbname=country_db", "root","");

 ?>
Index.php
<?php include "db.php"; ?>
<?php 

$Query = $db->prepare("SELECT * FROM country");
$Query->execute();
$rows = $Query->fetchAll(PDO::FETCH_OBJ);


 ?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>JSON Response</title>
 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
 
   <div class="container">
    <div class="box">
     <div class="group">
      <select id="cities" name="cities" class="control">
       <option value="">Choose Country</option>
       <?php foreach($rows as $show): ?>
        <option value="<?php echo $show->id; ?>"><?php echo $show->country_name; ?></option>
       <?php endforeach; ?>
      </select>
     </div><!-- close group -->
     <div class="group">
      <div class="result">
       
      </div><!-- close result -->
     </div><!-- close group -->
    </div><!-- close box -->
   </div><!-- close container -->

   <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
   <script type="text/javascript">
    $(document).ready(function(){
     $("#cities").click(function(){
      var id = $("#cities").val();
      if(id.length == ""){

      } else {
       $.ajax({
        type : 'POST',
        url  : 'country.php',
        data : {'id': id},
        dataType : 'JSON',
        success : function(response){
                    $(".result").css("display", "block");
                    $(".result").html("");
                    for(i = 0; i < response.length; i++){
 
                     $(".result").append(response[i]+"<br>");
         
        }
                    }

       })
      }
     })
    })
   </script>

</body>
</html>
Country.php
<?php 
include "db.php";
if(isset($_POST['id'])) {
 $id = $_POST['id'];
 $Query = $db->prepare("SELECT * FROM cities WHERE country_id = ?");
 $Query->execute([$id]);
 $data = [];

 $rows = $Query->fetchAll(PDO::FETCH_OBJ);
 foreach($rows as $result):
       
       $data[] = $result->city;

 endforeach;

 echo json_encode($data);
}


 ?>

COMMENTS

Name

ajax,1,HTML & CSS,12,PHP,7,
ltr
item
webtipstricks: PHP JSON To Array Fetch Country Cities
PHP JSON To Array Fetch Country Cities
PHP JSON To Array means how to use PHP with JSON, In this article we will fetch records from MySQL database and will return JSON array.
https://2.bp.blogspot.com/-XfkV8W0tY08/W1NvtslkI7I/AAAAAAAABsc/ApNO076xzn8E0bNd5-s8fwfY8mCcK8rWgCLcBGAs/s640/ajax%2Bfetch%2Bcities.png
https://2.bp.blogspot.com/-XfkV8W0tY08/W1NvtslkI7I/AAAAAAAABsc/ApNO076xzn8E0bNd5-s8fwfY8mCcK8rWgCLcBGAs/s72-c/ajax%2Bfetch%2Bcities.png
webtipstricks
https://www.webtipstricks.com/2018/05/json-response.html
https://www.webtipstricks.com/
https://www.webtipstricks.com/
https://www.webtipstricks.com/2018/05/json-response.html
true
4027471107773963481
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy