2024年03月28日 建站教程
1、连接数据库
$host = 'localhost'; $username = 'root'; $password = 'password'; $dbname = 'webnet'; // 创建数据库连接 $db = new mysqli($host, $username, $password, $dbname); // 检查连接是否成功 if ($db->connect_error) { die("连接失败: " . $db->connect_error); } else { echo "连接成功!"; }
2、查询数据
$sql = "SELECT * FROM table"; $result = $db->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . " "; } } else { echo "没有数据"; }
3、插入数据
$name = '小米'; $school = '清北'; $sql = "INSERT INTO table (name, school) VALUES ('$name', '$school')"; if ($db->query($sql) === TRUE) { echo "新记录插入成功!"; } else { echo "Error: " . $sql . "<br>" . $db->error; }
4、更新数据
$id = 10; $newName = 'Jane Doe'; $sql = "UPDATE table SET name='$newName' WHERE id=$id"; if ($db->query($sql) === TRUE) { echo "记录更新成功!"; } else { echo "Error: " . $sql . "<br>" . $db->error; }
本文链接:http://so.lmcjl.com/news/564/