首页 > 数据库 > mysql教程 > PHP CRUD 操作初学者指南

PHP CRUD 操作初学者指南

王林
发布: 2024-07-17 12:41:23
原创
1144 人浏览过

介绍

PHP 是一种灵活且广泛使用的服务器端脚本语言,为我们今天看到的许多动态和交互式网页提供支持。作为一名初学者,我发现学习 PHP 的旅程既充满挑战又充满收获。在这篇文章中,我们将在我上一篇文章中介绍的基础知识的基础上,探索 PHP 中更高级的主题。

如果您还没有阅读我的第一篇文章《PHP 入门:初学者指南》,我强烈建议您查看一下。它涵盖了 PHP 的基础知识,包括设置开发环境、理解基本语法以及使用变量和数据类型。

随着我们深入研究 PHP,我欢迎任何反馈、建议或更正。您的评论不仅帮助我进步,还为所有读者创造了一个协作学习的环境。让我们一起继续我们的 PHP 之旅!

设置 MySQL 数据库

在开始编码之前,我们需要设置一个 MySQL 数据库。如果您安装了 XAMPP,那么您已经成功了一半!

在 XAMPP 中配置 MySQL

  1. 打开 XAMPP 控制面板:启动 XAMPP 控制面板并启动“Apache”和“MySQL”服务。

  2. 打开 XAMPP 控制面板:启动 XAMPP 控制面板并启动“Apache”和“MySQL”服务。

  3. 创建数据库:

  • 点击左侧边栏的“新建”按钮。

  • 输入数据库名称,然后单击“创建”。

还有另一种选择,即通过编写 CREATE DATABASE database_name 创建数据库; SQL 脚本中的命令,然后单击 Go 命令。

这些步骤如下图所示。

Start the PHP and MySQL server with XAMPP

Open MySQL in XAMPP

创建数据库的第一个选项:
Create new database

在 SQL 脚本上使用 MySQL 命令创建数据库:
Create new database by using MySQL command

使用 phpMyAdmin 创建表

  1. 选择您的数据库:单击您刚刚创建的数据库。

  2. 创建表:

  • 输入表的名称(例如,用户)。

  • 指定列数并单击“开始”。

  • 定义列(例如,id、姓名、电子邮件、年龄)。

或者通过在 SQL 脚本中使用 MySQL 命令

CREATE TABLE users (
    id INT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL, 
    name VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL UNIQUE,
    age INT(3) NOT NULL
)
登录后复制


然后点击开始。

将 PHP 连接到 MySQL

使用 'mysqli' 连接到 MySQL

更新了下面的代码

<!-- Opening PHP tag to write PHP code -->
<?php

// Specifies the hostname of the MySQL server.
$servername = "localhost";

// The MySQL username. "root" is the default administrative username for MySQL.
$username = "root";

// The MySQL password for the specified user. It is empty ("") by default for the root user in many local development environments.
$password = "";

// The name of the database you want to connect to.
$dbname = "php_project";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    // Log the error and display a generic message to the user
    error_log("Connection failed: " . mysqli_connect_error());
    die("Connection failed. Please try again later.");
}

// If the connection is successful, display or log a success message
echo "Connected successfully";

// Close the connection (optional, as it will close when the script ends)
mysqli_close($conn);

?>

登录后复制

执行CRUD操作

在 Web 开发环境中执行 CRUD 操作是指可以对数据库中存储的数据执行的基本操作:创建、读取、更新和删除。这些操作对于构建用户可以与数据交互的动态和交互式 Web 应用程序至关重要。 CRUD 操作是 Web 应用程序中数据库交互的支柱。 PHP 允许您通过定义包含 SQL 代码的变量并使用 PHP 的数据库交互库(如 MySQLi

执行它们)来轻松执行这些操作

创建:插入数据

更新了代码 ↓

<?php
// Set a value for each variable. Variables type of values should be same as set in database
$name = "person1";
$email = "person1@example.com";
$age = 25;

// Prepare the SQL statement
$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email, age) VALUES ($name, $email, $age)");

// Bind parameters to the prepared statement
mysqli_stmt_bind_param($stmt, "ssi", $name, $email, $age);

// Execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
    echo "New record created successfully </br>";
} else {
    // Log the error for debugging purposes
    error_log("Error: " . mysqli_stmt_error($stmt));

    // Display a generic error message to the user
    echo "An error occurred while creating the record. Please try again later.";
}

// Close the prepared statement
mysqli_stmt_close($stmt);
登录后复制

阅读:获取数据

读取操作用于从数据库中获取数据。这通常是使用 SQL 中的 SELECT 语句来完成的。以下是如何在 PHP 中执行读取操作的分步代码和说明:

// Create an SQL query
$sql = "SELECT id, name, email, age FROM users";
$result = mysqli_query($conn, $sql);

// Check if there are any results
if (mysqli_num_rows($result) > 0) {
    // Fetch and output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. " - Age: " . $row["age"]. "<br>";
    }
} else {
    echo "0 results";
}
登录后复制

更新:修改数据

您是否曾经需要修改数据库中的现有数据?你是如何做到的?
PHP 中的更新操作用于修改 MySQL 数据库中的现有记录。这对于维护应用程序中准确且最新的数据至关重要。例如,如果用户的信息发生变化,例如他们的电子邮件地址或年龄,您将使用更新操作在数据库中反映这些更改。

更新了代码

<?php
// Assuming you already have a connection established in $conn

$newAge = 32;
$email = 'person1@example.com';

// Prepare an SQL statement
$stmt = mysqli_prepare($conn, "UPDATE users SET age=$newAge WHERE email=$email");

if ($stmt) {
    // Bind parameters to the prepared statement
    mysqli_stmt_bind_param($stmt, "is", $newAge, $email);

    // Execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        echo "Record updated successfully";
    } else {
        // Log the error internally, do not display it to the user
        error_log("Error executing statement: " . mysqli_stmt_error($stmt));
        echo "An error occurred while updating the record. Please try again later.";
    }

    // Close the statement
    mysqli_stmt_close($stmt);
} else {
    // Log the error internally, do not display it to the user
    error_log("Error preparing statement: " . mysqli_error($conn));
    echo "An error occurred. Please try again later.";
}

// Close the connection
mysqli_close($conn);
?>

登录后复制

根据上面编写的代码,如果更新过程顺利,我们将收到消息“记录更新成功”,在这种情况下,具有指定电子邮件的用户的年龄值将更改为 32,我们可以看到我们数据库中的结果。

Delete: Removing Data

The delete operation in PHP is used to remove records from a database table. This operation is performed using the SQL DELETE statement, which specifies the conditions under which records should be deleted. The syntax of the DELETE statement allows you to specify one or more conditions to ensure that only the intended records are removed from the database.

Updated code

<?php

$email = 'person3@example.com';

// Prepare an SQL statement
$stmt = mysqli_prepare($conn, "DELETE FROM users WHERE email=$email");

if ($stmt) {
    // Bind parameter to the prepared statement
    mysqli_stmt_bind_param($stmt, "s", $email);

    // Execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        // Verify if any records were deleted using mysqli_stmt_affected_rows
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            echo "Record deleted successfully";
        } else {
            echo "No record found with the specified email.";
        }
    } else {
        // Log the error internally, do not display it to the user
        error_log("Error executing statement: " . mysqli_stmt_error($stmt));
        echo "An error occurred while deleting the record. Please try again later.";
    }

    // Close the statement
    mysqli_stmt_close($stmt);
} else {
    // Log the error internally, do not display it to the user
    error_log("Error preparing statement: " . mysqli_error($conn));
    echo "An error occurred. Please try again later.";
}

// Close the connection
mysqli_close($conn);
?>
登录后复制

Further Reading:

  • Official PHP Documentation
  • W3Schools PHP Tutorial

Conclusion

CRUD operations are the backbone of database interactions in web applications. By mastering these operations, you can build dynamic and interactive applications. I'd love to hear about your experiences with CRUD operations! Share your thoughts in the comments below and let's keep the discussion going.

I want to express my sincere gratitude to each and every one of you who took the time to read this post and share your insights. Your engagement and feedback are incredibly valuable as we continue to learn and grow together.

Don't forget to check out my previous post for more foundational concepts, and feel free to leave your feedback or comments below. Thank you for joining me on this exploration of CRUD operations in PHP.

以上是PHP CRUD 操作初学者指南的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板