要连接MySQL数据库并获取数据,你可以使用PHP中的mysqli扩展或PDO扩展。下面是一个示例代码,演示如何连接MySQL数据库并获取数据:
- 使用mysqli扩展:
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 查询数据
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// 输出查询结果
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// 关闭连接
$conn->close();
- 使用PDO扩展:
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 查询数据
$stmt = $conn->prepare("SELECT * FROM table_name");
$stmt->execute();
// 输出查询结果
$result = $stmt->fetchAll();
foreach($result as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// 关闭连接
$conn = null;
以上是使用mysqli扩展和PDO扩展连接MySQL数据库并获取数据的示例代码。你可以根据自己的实际情况选择其中一种来使用。