How to use PHP to develop a simple online document editor function
With the popularity of the Internet, more and more people need to edit and share documents through the Internet. In order to meet this demand, it is necessary to develop a simple online document editor function. This article will introduce how to develop such a function using PHP and provide specific code examples.
Create database and table
First, we need to create a database and a table to store document data. Create a database named "documents" and create a table named "documents" in it to store the content of the document. The structure is as follows:
CREATE DATABASE documents; USE documents; CREATE TABLE documents ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100) NOT NULL, content TEXT NOT NULL );
Write PHP code
Next step, we will write PHP code to implement the function of the online document editor. First, create a file named "index.php" as our entry file. Add the following code to the file:
<?php // 连接到数据库 $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "documents"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("数据库连接出错:" . $conn->connect_error); } // 处理表单提交 if ($_SERVER["REQUEST_METHOD"] == "POST") { $title = $_POST["title"]; $content = $_POST["content"]; // 将文档保存到数据库 $sql = "INSERT INTO documents (title, content) VALUES ('$title', '$content')"; if ($conn->query($sql) === TRUE) { echo "文档保存成功!"; } else { echo "保存文档时出错:" . $conn->error; } } // 获取文档列表 $sql = "SELECT * FROM documents"; $result = $conn->query($sql); $conn->close(); ?> <!DOCTYPE html> <html> <head> <title>在线文档编辑器</title> </head> <body> <h1>在线文档编辑器</h1> <h2>创建新文档</h2> <form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>"> 标题:<input type="text" name="title"><br> 内容:<textarea name="content"></textarea><br> <input type="submit" value="保存文档"> </form> <h2>已有文档列表</h2> <?php if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "<h3>" . $row["title"] . "</h3>"; echo "<p>" . $row["content"] . "</p>"; } } else { echo "暂无文档"; } ?> </body> </html>
So far, we have completed the development of a simple online document editor. You can expand and improve this editor according to your own needs, such as adding deletion, editing and other functions. Hope this article is helpful to you!
The above is the detailed content of How to use PHP to develop a simple online document editor function. For more information, please follow other related articles on the PHP Chinese website!