1.SQL查询(SELECT):
<?php
$servername = "localhost"; // MySQL服务器名称或IP地址
$username = "root"; // MySQL用户名
$password = ""; // MySQL密码
$dbname = "myDB"; // 要连接的数据库名称
// 创建与MySQL数据库的连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 编写SQL查询语句
$sql = "SELECT * FROM myTable";
// 执行查询并获取结果集
$result = $conn->query($sql);
// 处理结果集
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. ", Name: " . $row["name"]. "<br>";
}
} else {
echo "No results found.";
}
// 关闭数据库连接
$conn->close();
?>
2.SQL插入(INSERT):
<?php
$servername = "localhost"; // MySQL服务器名称或IP地址
$username = "root"; // MySQL用户名
$password = ""; // MySQL密码
$dbname = "myDB"; // 要连接的数据库名称
// 创建与MySQL数据库的连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 编写SQL插入语句
$sql = "INSERT INTO myTable (name, age) VALUES ('John', '30')";
// 执行插入操作
if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
3.SQL更新(UPDATE):
<?php
$servername = "localhost"; // MySQL服务器名称或IP地址
$username = "root"; // MySQL用户名
$password = ""; // MySQL密码
$dbname = "myDB"; // 要连接的数据库名称
// 创建与MySQL数据库的连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 编写SQL更新语句
$sql = "UPDATE myTable SET name='Jane' WHERE id=1";
// 执行更新操作
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
4.SQL删除(DELETE):
<?php
$servername = "localhost"; // 数据库服务器名称
$username = "your_username"; // 数据库用户名
$password = "your_password"; // 数据库密码
$dbname = "your_database"; // 数据库名称
// 创建与数据库的连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//编写SQL语句来执行删除操作。根据需求选择合适的条件来指定要删除的记录。
//your_table应该被替换为要从其中删除记录的表格名称,
//而condition则是指定要删除的记录的条件。
$sql = "DELETE FROM your_table WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . $conn->error;
}
//最后,断开与数据库的连接。
$conn->close();
?>