php链接mysql
文章描述:
php链接MySQL数据库实现增、删、改、查功能
php版本7
创建链接
主机、用户名、密码、数据库名
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "laravel";
// 检测连接
try {
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
echo "连接成功";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
插入数据
向数据库插入一条数据,并返回插入数据的id信息,insert_id是php7中使用的方法,不同php版本用不同代码
$sql = "INSERT INTO myguests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
获取插入数据的id
echo "ID of last inserted record is: " . $conn->insert_id;
读取数据
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 输出数据
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 结果";
}
关闭链接
mysqli_close($conn);
更新数据
指定id更新一条信息
$name = "小明";
$conn->query("UPDATE users SET name='{$name}' WHERE id=6 ");
删除数据
指定id删除一条信息
$id = 7;
$conn->query("DELETE FROM users WHERE id='{$id}'");
发布时间:2023/04/25
发表评论