连接数据库
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname);
检查连接是否成功
if (!$conn) { die("连接失败: " . mysqli_connect_error()); }
查询数据
$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 结果"; }
插入数据
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
更新数据
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "记录更新成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
删除数据
$sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "记录删除成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
关闭连接
mysqli_close($conn);
安整的PHP代码
<?php // 连接数据库 $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查连接是否成功 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } // 查询数据 $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 结果"; } // 插入数据 $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 更新数据 $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "记录更新成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 删除数据 $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "记录删除成功"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // 关闭连接 mysqli_close($conn); ?>
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
评论