PHP是一種流行的伺服器端程式語言,它能夠輕鬆地與資料庫系統交互,是Web應用程式開發領域的首選。本文將探討如何使用PHP實現資料儲存與檢索功能。
一、使用PHP連接資料庫
PHP中使用mysqli函數連接資料庫,並且需要輸入使用者名稱、密碼和資料庫名稱。下面是一個連接資料庫的範例程式碼:
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databaseName = "my_database"; // 创建数据库连接 $connect = mysqli_connect($hostname, $username, $password, $databaseName); // 检查连接是否成功 if (!$connect) { die("连接失败: " . mysqli_connect_error()); } echo "连接成功"; ?>
二、使用PHP實作資料儲存功能
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databaseName = "my_database"; // 创建数据库连接 $connect = mysqli_connect($hostname, $username, $password, $databaseName); // 检查连接是否成功 if (!$connect) { die("连接失败: " . mysqli_connect_error()); } // 准备要插入的数据 $firstname = "John"; $lastname = "Doe"; $email = "john.doe@example.com"; // 向数据库表中插入数据 $sql = "INSERT INTO users (firstname, lastname, email) VALUES ('$firstname', '$lastname', '$email')"; if (mysqli_query($connect, $sql)) { echo "数据成功插入到数据库表中"; } else { echo "数据插入失败: " . mysqli_error($connect); } // 关闭数据库连接 mysqli_close($connect); ?>
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databaseName = "my_database"; // 创建数据库连接 $connect = mysqli_connect($hostname, $username, $password, $databaseName); // 检查连接是否成功 if (!$connect) { die("连接失败: " . mysqli_connect_error()); } // 更新数据 $sql = "UPDATE users SET firstname='Jim' WHERE id=1"; if (mysqli_query($connect, $sql)) { echo "数据成功更新到数据库表中"; } else { echo "数据更新失败: " . mysqli_error($connect); } // 关闭数据库连接 mysqli_close($connect); ?>
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databaseName = "my_database"; // 创建数据库连接 $connect = mysqli_connect($hostname, $username, $password, $databaseName); // 检查连接是否成功 if (!$connect) { die("连接失败: " . mysqli_connect_error()); } // 删除数据 $sql = "DELETE FROM users WHERE id=1"; if (mysqli_query($connect, $sql)) { echo "数据成功从数据库表中删除"; } else { echo "数据删除失败: " . mysqli_error($connect); } // 关闭数据库连接 mysqli_close($connect); ?>
<?php $hostname = "localhost"; $username = "root"; $password = ""; $databaseName = "my_database"; // 创建数据库连接 $connect = mysqli_connect($hostname, $username, $password, $databaseName); // 检查连接是否成功 if (!$connect) { die("连接失败: " . mysqli_connect_error()); } // 查询数据 $sql = "SELECT * FROM users"; $result = mysqli_query($connect, $sql); if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "username: " . $row["username"] . " - email: " . $row["email"] . "<br>"; } } else { echo "0 结果"; } // 关闭数据库连接 mysqli_close($connect); ?>
以上是如何使用PHP實現資料儲存和檢索功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!