php语言之mysql操作答案
时间: 2023-07-22 13:18:32 浏览: 215
好的,我来回答你的问题。PHP语言可以通过MySQL扩展库来连接和操作MySQL数据库。以下是连接和查询MySQL数据库的示例代码:
连接MySQL数据库:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// 创建连接
$conn = new mysqli($servername, $username, $password);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
?>
```
查询MySQL数据库:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询数据
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
```
以上是基本的连接和查询MySQL数据库的代码示例,希望能对你有所帮助。
阅读全文