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

Angular JS结合Ionic框架:通过JSON向MySQL插入数据失败

Hey there, let's break down why your MySQL insert isn't working and fix it step by step. Looking at your code snippet, I spot a few common issues that could be causing the failure:

1. Incorrect Parameter Types

You're passing Int32Array for questionid and questionanswer, but if these are single numeric values (like a single question ID or answer choice), this is the wrong type. Int32Array is a typed array for multiple integers, while your backend is almost certainly expecting individual number values.

Fix: Change the parameter types to number instead:

createEntry(questionid: number, questionanswer: number): void {
  // ... rest of your code
}
2. Missing HTTP Request Method & Error Handling

Your code sets up headers and options, but there's no actual HTTP call implementation. Without specifying a POST method (required for inserting data), the request might default to GET, which can't send a payload properly. Plus, adding error handling will help you pinpoint exactly what's breaking.

Here's the full corrected implementation with HttpClient:

import { HttpClient, HttpHeaders } from '@angular/common/http';
// Make sure you've injected HttpClient in your component/service constructor

constructor(private http: HttpClient) {}

createEntry(questionid: number, questionanswer: number): void {
  const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  const payload = { 
    "key": "create", 
    "user": 'test', 
    "questionid": questionid, 
    "questionanswer": questionanswer 
  };
  const url = "http://www.so-ta.de/brkwrkt2018/manage-data.php";

  // Send POST request with proper error handling
  this.http.post(url, payload, { headers: headers })
    .subscribe({
      next: (response) => {
        console.log('Insert successful:', response);
        // Add success UI feedback here (e.g., Ionic toast)
      },
      error: (error) => {
        console.error('Insert failed:', error);
        // This will show you the exact issue (CORS, invalid params, server error, etc.)
      }
    });
}
3. Backend PHP Validation

Your manage-data.php script needs to correctly parse the JSON payload and handle the insert. Common mistakes here include using $_POST directly (Angular sends JSON in the request body, not form data) and missing CORS headers.

Here's a corrected PHP snippet:

// Handle CORS (restrict to your frontend domain in production!)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

// Read JSON payload
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
  echo json_encode(["success" => false, "message" => "Invalid JSON input"]);
  exit;
}

// Extract parameters with defaults
$key = $input['key'] ?? '';
$user = $input['user'] ?? '';
$questionid = (int)$input['questionid'] ?? 0;
$questionanswer = (int)$input['questionanswer'] ?? 0;

if ($key === 'create') {
  // Connect to MySQL (replace with your credentials)
  $conn = new mysqli('your_db_host', 'your_db_user', 'your_db_pass', 'your_db_name');
  
  // Use prepared statements to prevent SQL injection
  $stmt = $conn->prepare("INSERT INTO your_table_name (user, questionid, questionanswer) VALUES (?, ?, ?)");
  $stmt->bind_param("sii", $user, $questionid, $questionanswer);
  
  if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Entry created successfully"]);
  } else {
    echo json_encode(["success" => false, "message" => "MySQL error: " . $conn->error]);
  }
  
  $stmt->close();
  $conn->close();
} else {
  echo json_encode(["success" => false, "message" => "Invalid key parameter"]);
}
4. Debugging Steps to Confirm Fix

If it still fails, use these steps to diagnose:

  • Open your browser's DevTools > Network tab: Check the request payload to ensure values are sent correctly, and look at the server's response for error details.
  • Test the PHP endpoint directly with Postman: Send a POST request with the JSON body {"key":"create","user":"test","questionid":1,"questionanswer":2} to rule out frontend issues.
  • Verify MySQL credentials and table structure: Ensure your table has columns matching user, questionid, and questionanswer, and that the database user has insert permissions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:15:24