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

Angular调用PHP-MySQL API更新Partenaire时出现未定义数组键警告

问题分析与解决思路

核心原因

你的PHP API用parse_str(file_get_contents('php://input'), $post_input)解析PUT请求体,但Angular的HttpClient默认发送JSON格式的请求数据,parse_str只能解析application/x-www-form-urlencoded类型的表单数据,导致$post_input为空数组,触发"Undefined array key"警告。而PostMan测试时你应该用了表单格式,所以能正常运行。


解决方法(推荐第一种)

方法1:PHP端适配JSON请求格式

修改PHP中解析请求体的逻辑,改用JSON解码:

if ($api == 'PUT') {
  // 读取并解码JSON格式的请求体
  $post_input = json_decode(file_get_contents('php://input'), true);

  // 先校验请求数据有效性
  if (!$post_input) {
    echo $tuple->message('无效的请求数据格式', true);
    exit;
  }

  // 给每个字段添加isset判断,避免未定义键警告
  $g01 = isset($post_input['nomfranchise']) ? $tuple->test_input($post_input['nomfranchise']) : '';
  $g02 = isset($post_input['sexegerant']) ? $tuple->test_input($post_input['sexegerant']) : '';
  $g03 = isset($post_input['nomgerant']) ? $tuple->test_input($post_input['nomgerant']) : '';
  $g04 = isset($post_input['mail']) ? $tuple->test_input($post_input['mail']) : '';
  $g05 = isset($post_input['password']) ? $tuple->test_input($post_input['password']) : '';
  $g06 = isset($post_input['actif']) ? $tuple->test_input($post_input['actif']) : '';
  $g07 = isset($post_input['grants']) ? $tuple->test_input($post_input['grants']) : '';

  // 后续更新逻辑保持不变
  if ($id != null) {
    if ($tuple->update($g01, $g02, $g03, $g04, $g05, $g06, $g07, $id)) {
      echo $tuple->message('Partenaire modifié avec succès !',false);
    } else {
      echo $tuple->message('Erreur lors de la modification du partenaire !',true);
    }
  } else {
    echo $tuple->message('Partenaire non trouvé !',true);
  }
}

方法2:Angular端发送表单格式数据

如果不想修改PHP,可以让Angular发送application/x-www-form-urlencoded格式的请求:

修改ApiService中的updatePartenaire方法:

updatePartenaire(id: number, partenaire: Partenaire): Observable<Partenaire>{
  let headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded'
  });
  this.createAuthorizationHeader(headers);
  
  // 将Partenaire对象转换为表单参数
  const body = new HttpParams()
    .set('nomfranchise', partenaire.nomfranchise)
    .set('sexegerant', partenaire.sexegerant)
    .set('nomgerant', partenaire.nomgerant)
    .set('mail', partenaire.mail)
    .set('password', partenaire.password)
    .set('actif', partenaire.actif)
    .set('grants', partenaire.grants);

  return this.httpClient.put<Partenaire>(`${this.PHP_API_SERVER}partenaire.php/${id}`, body.toString(), { headers : headers, responseType: "json" });
}

额外检查项

  • 确认Angular的Partenaire接口字段名与PHP端使用的键名完全一致(注意大小写、拼写)
  • 确保PHP的test_input方法能正确处理空值输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:05:48