在PHP中使用MySQL将行更改为列可以通过以下步骤实现:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 使用MySQLi扩展
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 使用PDO扩展
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
?>
使用PIVOT:
SELECT
MAX(CASE WHEN column_name = 'name' THEN column_value END) AS name,
MAX(CASE WHEN column_name = 'age' THEN column_value END) AS age,
MAX(CASE WHEN column_name = 'gender' THEN column_value END) AS gender
FROM
your_table
GROUP BY
row_id;
使用CASE:
SELECT
MAX(CASE column_name WHEN 'name' THEN column_value END) AS name,
MAX(CASE column_name WHEN 'age' THEN column_value END) AS age,
MAX(CASE column_name WHEN 'gender' THEN column_value END) AS gender
FROM
your_table
GROUP BY
row_id;
请注意,上述查询需要根据实际的表结构和数据进行适当的修改。
使用MySQLi:
<?php
$sql = "SELECT ..."; // 编写SQL查询
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Age: " . $row["age"]. " - Gender: " . $row["gender"]. "<br>";
}
} else {
echo "没有结果";
}
$conn->close();
?>
使用PDO:
<?php
$sql = "SELECT ..."; // 编写SQL查询
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
// 输出每行数据
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "Name: " . $row["name"]. " - Age: " . $row["age"]. " - Gender: " . $row["gender"]. "<br>";
}
} else {
echo "没有结果";
}
$conn = null;
?>
这样,你就可以使用PHP和MySQL将行更改为列。请根据实际需求和表结构进行相应的修改和调整。
相关链接:
领取专属 10元无门槛券
手把手带您无忧上云