在PHP中,可以使用MySQLi或PDO来访问MySQL数据库。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 执行查询
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// 处理结果集
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "字段1: " . $row["column1"]. " - 字段2: " . $row["column2"]. "<br>";
}
} else {
echo "0 结果";
}
// 关闭连接
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 执行查询
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
// 处理结果集
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "字段1: " . $row["column1"]. " - 字段2: " . $row["column2"]. "<br>";
}
} else {
echo "0 结果";
}
// 关闭连接
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 执行查询
$sql = "SELECT * FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
// 处理结果集
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) > 0) {
foreach($result as $row) {
echo "字段1: " . $row["column1"]. " - 字段2: " . $row["column2"]. "<br>";
}
} else {
echo "0 结果";
}
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 关闭连接
$conn = null;
?>
以上示例中的变量值需要根据实际情况进行替换,其中$servername
为MySQL服务器名,$username
为数据库用户名,$password
为数据库密码,$dbname
为数据库名。
推荐的腾讯云相关产品和产品介绍链接地址:
请注意,以上仅为示例,实际使用中应根据具体需求选择合适的产品和配置。
领取专属 10元无门槛券
手把手带您无忧上云