You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP和Vue JS筛选MySQL数据库中的指定国家用户数据

实现按特定国家筛选用户数据的方案

一、后端PHP修改(处理请求的API文件)

修改接收请求的PHP文件,支持接收国家筛选参数,并通过预处理语句安全构建查询条件:

<?php
include "config.php";

// 初始化条件数组与参数容器
$conditions = [];
$params = [];
$types = "";

// 处理userid筛选逻辑
if(isset($_GET['userid']) && trim($_GET['userid']) !== ""){
    $userid = (int)$_GET['userid'];
    $conditions[] = "id = ?";
    $params[] = $userid;
    $types .= "i"; // 标记参数为整数类型
}

// 处理多国家筛选逻辑
if(isset($_GET['countries']) && is_array($_GET['countries']) && !empty($_GET['countries'])){
    // 生成IN语句对应的占位符
    $placeholders = implode(', ', array_fill(0, count($_GET['countries']), '?'));
    $conditions[] = "country IN ($placeholders)";
    // 合并国家参数并标记类型为字符串
    $params = array_merge($params, $_GET['countries']);
    $types .= str_repeat('s', count($_GET['countries']));
}

// 构建完整SQL语句
$whereClause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";
$sql = "SELECT * FROM users $whereClause";

// 执行预处理查询
$stmt = mysqli_prepare($con, $sql);
if($stmt){
    if(!empty($params)){
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    }
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $response = [];
    while($row = mysqli_fetch_assoc($result)){
        $response[] = $row;
    }
    
    mysqli_stmt_close($stmt);
} else {
    $response = ['error' => 'SQL语句构建失败: ' . mysqli_error($con)];
}

echo json_encode($response);
exit;
?>

二、前端Vue代码修改

添加国家筛选的交互逻辑,包括数据变量、UI元素和请求方法:

1. 更新Vue实例的data与methods

<script>
var app = new Vue({
  el: '#app',
  data: {
    users: "",
    userid: 0,
    // 可选国家列表,可根据实际需求扩展
    availableCountries: ["United States", "Japan", "France", "Sweden"],
    // 存储用户选中的国家
    selectedCountries: []
  },
  methods: {
    allRecords: function(){
      axios.get('api.php')
      .then(function (response) {
          app.users = response.data;
      })
      .catch(function (error) {
          console.log(error);
      });
    },
    recordByID: function(){
      if(this.userid > 0){
        axios.get('api.php', {
            params: {
                userid: this.userid
            }
        })
          .then(function (response) {
            app.users = response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
    // 新增:按选中国家筛选的方法
    filterByCountries: function(){
      if(this.selectedCountries.length > 0){
        axios.get('api.php', {
            params: {
                countries: this.selectedCountries
            }
        })
          .then(function (response) {
            app.users = response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        // 未选中任何国家时加载全量数据
        this.allRecords();
      }
    }
  }
});
</script>

2. 添加对应的UI交互元素(在#app容器内)

<div id="app">
  <!-- 按ID筛选区域 -->
  <div>
    <input type="number" v-model="userid" placeholder="输入用户ID">
    <button @click="recordByID">按ID查询</button>
  </div>

  <!-- 按国家筛选区域 -->
  <div>
    <h3>选择筛选国家:</h3>
    <div v-for="country in availableCountries" :key="country">
      <label>
        <input type="checkbox" v-model="selectedCountries" :value="country">
        {{ country }}
      </label>
    </div>
    <button @click="filterByCountries">按国家筛选</button>
  </div>

  <!-- 用户列表展示 -->
  <div v-if="users">
    <h3>用户列表:</h3>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.first_name }} {{ user.last_name }} - {{ user.country }} ({{ user.email }})
      </li>
    </ul>
  </div>
</div>

关键说明

  • 安全保障:采用MySQLi预处理语句绑定参数,彻底规避SQL注入风险,比字符串拼接+转义的方式更可靠。
  • 功能兼容:同时支持按ID和按国家筛选,若同时传递两个参数,会返回满足双重条件的用户数据。
  • 灵活扩展:前端的availableCountries可改为从后端接口动态获取,无需硬编码固定值。

内容的提问来源于stack exchange,提问作者Justin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:48:24