如何在PHP中通过JSON传输数据?本地运行示例报错求助
Hey there! Let's break down your questions and fix that error step by step.
如何在PHP中通过JSON发送数据
Sending JSON data from PHP to the client is straightforward—here's how you do it:
- Set the correct response header
First, tell the client that you're sending JSON by setting theContent-Typeheader. This ensures the browser/JS interprets the response correctly (this line must come before any other output). - Prepare your data
Use a PHP array or object to hold your data, then convert it to a JSON string withjson_encode(). - Output the JSON
Echo the encoded string, and you're done!
Example: Basic JSON response
<?php // Set response header header("Content-Type: application/json; charset=UTF-8"); // Sample data $responseData = [ "status" => "success", "user" => [ "name" => "Alice", "email" => "alice@example.com" ] ]; // Encode and send echo json_encode($responseData); ?>
Example: Receive JSON from frontend (POST request)
If you're getting JSON from the client (like a POST request), use php://input to read the raw data, then parse it with json_decode():
<?php header("Content-Type: application/json; charset=UTF-8"); // Read raw JSON input $rawInput = file_get_contents('php://input'); $requestData = json_decode($rawInput, true); // true converts to associative array // Process data and send response $response = [ "receivedData" => $requestData, "message" => "Data received successfully" ]; echo json_encode($response); ?>
Fixing the bind_param() Fatal Error
Let's diagnose that error first: Call to a member function bind_param() on bool means your $conn->prepare() call returned false—so the prepared statement failed to create. Here's why, and how to fix it:
Why it's failing
- You can't bind table names with prepared statements
MySQL prepared statements only let you bind data values (likeWHERE id = ?), not structural parts of the query like table names or column names. Using?for the table name breaks the query entirely. - Incorrect parameter type for LIMIT
You used"ss"to bind$obj->limitas a string, but LIMIT expects an integer. This mismatch also causes issues with the prepared statement.
Fixed PHP Code
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); $conn = new mysqli("localhost", "root", "", "blog"); // Check database connection first if ($conn->connect_error) { echo json_encode(["error" => "Database connection failed: " . $conn->connect_error]); exit; } // Validate table name to prevent SQL injection (critical!) $allowedTables = ["users"]; // Add your actual table names here if (!in_array($obj->table, $allowedTables)) { echo json_encode(["error" => "Invalid table name"]); exit; } // Build query with validated table name, use placeholder for LIMIT $stmt = $conn->prepare("SELECT name FROM " . $obj->table . " LIMIT ?"); // Bind LIMIT as integer (use "i" for integer type) $stmt->bind_param("i", $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); // Clean up resources $stmt->close(); $conn->close(); ?>
Key fixes explained:
- Table name validation: We use a whitelist (
$allowedTables) to make sure the incoming table name is one you explicitly allow. This prevents SQL injection attacks that could happen if you directly concatenated user input without checking. - LIMIT parameter type: We use
"i"instead of"s"to bind the limit as an integer, which matches what MySQL expects for LIMIT. - Connection check: Added a check to catch database connection errors early, so you can debug those before worrying about the query.
内容的提问来源于stack exchange,提问作者Hassan
相关产品推荐
相关产品推荐

