You can use the mysqli or PDO extensions in PHP to query a single SQL record. Below are example codes for both methods:
Use the mysqli extension to query a single SQL record.
// 创建连接
$conn = mysqli_connect("localhost", "username", "password", "dbname");
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 执行查询
$sql = "SELECT * FROM mytable WHERE id = 1";
$result = mysqli_query($conn, $sql);
// 获取结果
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
// 输出结果
echo "id: " . $row["id"] . " - 名称: " . $row["name"] . " - 描述: " . $row["description"];
} else {
echo "没有找到数据";
}
// 关闭连接
mysqli_close($conn);Use the PDO extension to query a single SQL record:
// 创建连接
$dsn = "mysql:host=localhost;dbname=mydb;charset=utf8mb4";
$username = "username";
$password = "password";
try {
$conn = new PDO($dsn, $username, $password);
// 设置错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 执行查询
$sql = "SELECT * FROM mytable WHERE id = 1";
$stmt = $conn->query($sql);
// 获取结果
if ($stmt->rowCount() > 0) {
$row = $stmt->fetch();
// 输出结果
echo "id: " . $row["id"] . " - 名称: " . $row["name"] . " - 描述: " . $row["description"];
} else {
echo "没有找到数据";
}
// 关闭连接
$conn = null;This sample code assumes that the table to be queried is named "mytable", which contains three columns: "id", "name", and "description". In these examples, the query condition is `id = 1`; you can modify both the query condition and the way the output is formatted according to your specific requirements.