PHP数据库数据返回脚本报500错误,请求排查问题
Alright, let's break down why you're hitting that 500 Internal Server Error. These errors are tricky because they hide specific issues by default, but we can uncover the root cause with a few targeted checks and fixes.
Step 1: Turn on Error Reporting to See the Exact Issue
First, let's make PHP show us what's actually going wrong. Add these lines at the very top of your script (before require 'connect-mysql.php'):
<?php error_reporting(E_ALL); ini_set('display_errors', 1); // rest of your code follows
This will reveal specific errors like undefined variables, invalid JSON parsing, or SQL syntax issues that are triggering the 500 error.
Step 2: Fix JSON Retrieval and Decoding
A common gotcha here is how you're fetching the JSON data. If your client sends the JSON with a Content-Type: application/json header, $_POST['json'] will be empty—PHP doesn't auto-parse JSON into $_POST in that case. Instead, you need to read the raw request input:
$json = file_get_contents('php://input'); $array = json_decode($json); // Always validate that JSON decoding worked if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON: ' . json_last_error_msg()]); exit; } // Make sure the array and user_id exist if (!is_array($array) || empty($array[0]->user_id)) { http_response_code(400); echo json_encode(['error' => 'Missing or invalid user_id']); exit; } $id = $array[0]->user_id;
If you prefer working with associative arrays instead of objects, pass true as the second parameter to json_decode:
$array = json_decode($json, true); $id = $array[0]['user_id'];
Step 3: Fix Your SQL Query and Avoid Injection
Your snippet cuts off the SELECT query, but even if it's complete, directly inserting $id into the query is risky (SQL injection) and can cause syntax errors if the ID has special characters. Use prepared statements instead—they're safer and prevent syntax mishaps:
// Assuming $conn is your database connection from connect-mysql.php $stmt = $conn->prepare("SELECT * FROM your_table_name WHERE user_id = ?"); $stmt->bind_param("s", $id); // Use "i" instead of "s" if user_id is an integer $stmt->execute(); $result = $stmt->get_result(); // Fetch the query results $response = []; while ($row = $result->fetch_assoc()) { $response[] = $row; } // Clean up the statement $stmt->close();
Also, double-check that connect-mysql.php is properly establishing a connection—add a failure check there to catch connection issues early:
// Inside connect-mysql.php $conn = mysqli_connect("your_host", "your_user", "your_password", "your_db"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
Step 4: Ensure Proper JSON Output
When returning the JSON response, set the correct Content-Type header to avoid parsing issues, and make sure there's no extra output (like whitespace or warnings) before the JSON:
header('Content-Type: application/json'); echo json_encode($response);
Full Fixed Script Example
Putting it all together, here's a robust version of your script:
<?php error_reporting(E_ALL); ini_set('display_errors', 1); require 'connect-mysql.php'; // Get raw JSON input $json = file_get_contents('php://input'); $array = json_decode($json); // Validate JSON if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON: ' . json_last_error_msg()]); exit; } // Validate user_id exists if (!is_array($array) || empty($array[0]->user_id)) { http_response_code(400); echo json_encode(['error' => 'Missing or invalid user_id']); exit; } $id = $array[0]->user_id; // Prepare and execute SQL query $stmt = $conn->prepare("SELECT * FROM your_table WHERE user_id = ?"); $stmt->bind_param("s", $id); $stmt->execute(); $result = $stmt->get_result(); $response = []; while ($row = $result->fetch_assoc()) { $response[] = $row; } $stmt->close(); $conn->close(); // Return JSON response header('Content-Type: application/json'); echo json_encode($response); ?>
内容的提问来源于stack exchange,提问作者Luke Varty

