Home > Backend Development > PHP Problem > PHP three-level linkage implementation steps

PHP three-level linkage implementation steps

王林
Release: 2023-05-24 15:45:37
Original
865 people have browsed it

PHP three-level linkage implementation steps

With the development of the Internet, Web development has become an important part of the IT industry. As an important tool for web development, PHP has an increasingly wide range of applications. In web development, three-level linkage form controls are very useful in some special occasions, such as provincial and municipal address selection, brand, model, version selection, etc. In this article, we will briefly introduce the steps to implement PHP three-level linkage.

1. What is a three-level linkage control?

The three-level linkage control refers to displaying a linkage selection list on the front page. For example, when selecting a region, first select the province, and then based on Choose the province, then choose the city, and finally choose the district or county based on the city's choice. This three-level linkage control is very useful in some special occasions.

Second- and third-level linkage implementation technologies

There are many technologies for implementing third-level linkage, common ones include Ajax, jQuery, Vue.js, etc. We do not introduce these technologies here, but introduce a simple and easy-to-use PHP implementation method.

Three and three-level linkage implementation steps

Let’s briefly introduce the steps to achieve three-level linkage.

1. Write an HTML page

First we need to write an HTML page that contains drop-down boxes for provinces, cities, and counties. As shown below:

<!DOCTYPE html>
<html>
<head>
    <title>三级联动控件</title>
    <meta charset="UTF-8">
</head>
<body>
    <select id="province" name="province">
        <option value="0">请选择省份</option>
        <option value="1">北京</option>
        <option value="2">上海</option>
        <option value="3">广东</option>
        <!-- 其他省份省略 -->
    </select>
    <br><br>
    
    <select id="city" name="city">
        <option value="0">请选择城市</option>
    </select>
    <br><br>

    <select id="district" name="district">
        <option value="0">请选择县区</option>
    </select>
    <br><br>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>
Copy after login

2. Write JavaScript code

Next we write a JavaScript file to handle three-level linkage events. As shown below:

$(function(){
    // 省份下拉框改变事件
    $('#province').change(function(){
        var pid = $(this).val(); // 获取选中的省份id
        if(pid == 0){ // 如果省份id为0,则清空城市下拉框和县区下拉框
            $('#city').empty().append('<option value="0">请选择城市</option>');
            $('#district').empty().append('<option value="0">请选择县区</option>');
            return;
        }
        
        $.ajax({
            type: 'post',
            url: 'get_city.php', // 服务器处理程序,可根据需要修改
            data: {pid:pid},
            dataType: 'json',
            success: function(citys){
                $('#city').empty().append('<option value="0">请选择城市</option>');
                $('#district').empty().append('<option value="0">请选择县区</option>');
                $.each(citys, function(i, city){
                    $('#city').append('<option value="'+city.id+'">'+city.name+'</option>');
                });
            }
        });
    });
    
    // 城市下拉框改变事件
    $('#city').change(function(){
        var cid = $(this).val(); // 获取选中的城市id
        if(cid == 0){ // 如果城市id为0,则清空县区下拉框
            $('#district').empty().append('<option value="0">请选择县区</option>');
            return;
        }
        
        $.ajax({
            type: 'post',
            url: 'get_district.php', // 服务器处理程序,可根据需要修改
            data: {cid:cid},
            dataType: 'json',
            success: function(districts){
                $('#district').empty().append('<option value="0">请选择县区</option>');
                $.each(districts, function(i, district){
                    $('#district').append('<option value="'+district.id+'">'+district.name+'</option>');
                });
            }
        });
    });
});
Copy after login

3. Write a server-side handler

Finally, we also need to write a server-side handler for querying city and county data. As shown below:

get_city.php

<?php
header('Content-Type: application/json;charset=utf-8');
$pid = $_POST['pid'];
if(empty($pid)){
    echo json_encode([]);
    exit;
}

// 连接数据库查询城市数据
$conn = new mysqli('localhost', 'root', '123456', 'test');
if(mysqli_connect_errno()){
    echo json_encode([]);
    exit;
}

$conn->set_charset('utf8');
$sql = "select * from city where pid=".$pid;
$result = $conn->query($sql);
$citys = [];
while($row = $result->fetch_assoc()){
    $citys[] = $row;
}

echo json_encode($citys);
exit;
?>
Copy after login

get_district.php

<?php
header('Content-Type: application/json;charset=utf-8');
$cid = $_POST['cid'];
if(empty($cid)){
    echo json_encode([]);
    exit;
}

// 连接数据库查询县区数据
$conn = new mysqli('localhost', 'root', '123456', 'test');
if(mysqli_connect_errno()){
    echo json_encode([]);
    exit;
}

$conn->set_charset('utf8');
$sql = "select * from district where cid=".$cid;
$result = $conn->query($sql);
$districts = [];
while($row = $result->fetch_assoc()){
    $districts[] = $row;
}

echo json_encode($districts);
exit;
?>
Copy after login

4. Summary

In this article, we introduced PHP three-level linkage implementation steps. By implementing this function, we can build a three-level linkage selector for urban areas, making it more convenient and faster for users to select addresses. Using PHP technology to implement three-level linkage controls requires the cooperation of the front and back ends. The front end mainly implements page display and event processing functions, while the back end is mainly responsible for querying the database to obtain data. The method introduced in this article is just one of the implementation methods, and readers can improve and optimize it as needed.

The above is the detailed content of PHP three-level linkage implementation steps. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template