使用PHP的prepared statement从MySQL返回JSON格式的对象数组,可以按照以下步骤进行操作:
$servername = "数据库服务器地址";
$username = "数据库用户名";
$password = "数据库密码";
$dbname = "数据库名";
// 使用mysqli扩展连接到MySQL数据库
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 使用PDO扩展连接到MySQL数据库
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("连接失败: " . $e->getMessage());
}
json_encode()
函数将结果转换为JSON格式。以下是一个示例:$stmt = $conn->prepare("SELECT column1, column2 FROM table WHERE condition = ?");
$stmt->bind_param("s", $condition);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
$json = json_encode($data);
header('Content-Type: application/json');
echo $json;
完整的示例代码如下:
$servername = "数据库服务器地址";
$username = "数据库用户名";
$password = "数据库密码";
$dbname = "数据库名";
// 使用mysqli扩展连接到MySQL数据库
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 使用PDO扩展连接到MySQL数据库
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("连接失败: " . $e->getMessage());
}
$stmt = $conn->prepare("SELECT column1, column2 FROM table WHERE condition = ?");
$stmt->bind_param("s", $condition);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
$json = json_encode($data);
header('Content-Type: application/json');
echo $json;
这样,你就可以使用PHP的prepared statement从MySQL返回JSON格式的对象数组了。请注意,上述示例中的数据库连接和查询语句需要根据实际情况进行修改。
领取专属 10元无门槛券
手把手带您无忧上云