在PHP7中,我们通常使用mysqli或PDO扩展来操作MySQL数据库,以下是一些基本操作的示例:
(图片来源网络,侵删)1、连接数据库
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn>connect_error) { die("连接失败: " . $conn>connect_error); } echo "连接成功"; ?>
2、查询数据
<?php $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(); ?>
3、插入数据
<?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; } $conn>close(); ?>
4、更新数据
<?php $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if ($conn>query($sql) === TRUE) { echo "记录更新成功"; } else { echo "更新错误: " . $conn>error; } $conn>close(); ?>
5、删除数据
<?php $sql = "DELETE FROM MyGuests WHERE id=1"; if ($conn>query($sql) === TRUE) { echo "记录删除成功"; } else { echo "删除错误: " . $conn>error; } $conn>close(); ?>
最新评论
本站CDN与莫名CDN同款、亚太CDN、速度还不错,值得推荐。
感谢推荐我们公司产品、有什么活动会第一时间公布!
我在用这类站群服务器、还可以. 用很多年了。