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

如何在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:

  1. Set the correct response header
    First, tell the client that you're sending JSON by setting the Content-Type header. This ensures the browser/JS interprets the response correctly (this line must come before any other output).
  2. Prepare your data
    Use a PHP array or object to hold your data, then convert it to a JSON string with json_encode().
  3. 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

  1. You can't bind table names with prepared statements
    MySQL prepared statements only let you bind data values (like WHERE id = ?), not structural parts of the query like table names or column names. Using ? for the table name breaks the query entirely.
  2. Incorrect parameter type for LIMIT
    You used "ss" to bind $obj->limit as 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:13:25