Home  >  Article  >  Database  >  Use Smarty template engine to optimize PHP and MySQL development

Use Smarty template engine to optimize PHP and MySQL development

PHPz
PHPzOriginal
2023-07-01 10:00:371317browse

PHP development skills: How to use Smarty template engine to operate MySQL database

Introduction:
In PHP development, operating databases is a common requirement. The use of Smarty template engine can effectively separate the back-end logic from the front-end display, improving the maintainability and readability of the code. This article will introduce how to use the Smarty template engine to operate the MySQL database to implement operations such as adding, deleting, modifying, and querying data.

1. Preparation
Before starting, we need to prepare the following conditions in advance:

  1. Install and configure the PHP environment;
  2. Install and configure Good Smarty template engine;
  3. Create a MySQL database and import test data.

2. Connect to the database
Before we start, we need to connect to the database first. First, create a config.php file in the project to store the relevant configuration of the database connection. In the config.php file, we can define some constants to store information such as the database's host address, user name, password, and database name.

<?php
define('DB_HOST', 'localhost');  // 数据库主机地址
define('DB_USER', 'root');       // 数据库用户名
define('DB_PASS', 'password');   // 数据库密码
define('DB_NAME', 'test');       // 数据库名

// 数据库连接
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// 检查连接是否成功
if (!$conn) {
    die("连接失败:" . mysqli_connect_error());
}

3. Query data
Next, we can use the Smarty template engine to query the data in the database and display it on the front end. For the convenience of demonstration, we take querying and displaying the student list as an example.

First, we need to create a Smarty template file named "students.tpl" in the project. In this file, we can define the HTML structure and Smarty template syntax to display the student list.

Next, in the PHP code, we can obtain the data of the student list by querying the database and pass the data to the Smarty template engine.

<?php
require_once('config.php');
require_once('smarty/libs/Smarty.class.php');

$smarty = new Smarty();

$query = "SELECT * FROM students";
$result = mysqli_query($conn, $query);

// 将查询结果传递给Smarty模板引擎
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

$smarty->assign('students', $data);
$smarty->display('students.tpl');

In the "students.tpl" file, we can use Smarty template syntax to dynamically display the student list.

<!DOCTYPE html>
<html>
<head>
    <title>学生列表</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
            </tr>
        </thead>
        <tbody>
            {foreach $students as $student}
                <tr>
                    <td>{$student.id}</td>
                    <td>{$student.name}</td>
                    <td>{$student.gender}</td>
                    <td>{$student.age}</td>
                </tr>
            {/foreach}
        </tbody>
    </table>
</body>
</html>

4. Insert data
In addition to querying data, we can also use the Smarty template engine to insert new data into the database.

First, we need to define a form in the "add_student.tpl" file for users to enter student information, and then submit the data to the server through a POST request.

Next, in the PHP code, we can determine whether there is a POST request, and then obtain the data in the form and insert the data into the database.

<!DOCTYPE html>
<html>
<head>
    <title>添加学生</title>
</head>
<body>
    <form method="post" action="add_student.php">
        <label for="name">姓名:</label>
        <input type="text" name="name" required><br>
        <label for="gender">性别:</label>
        <input type="radio" name="gender" value="1" required>男
        <input type="radio" name="gender" value="0" required>女<br>
        <label for="age">年龄:</label>
        <input type="number" name="age" min="0" required><br>
        <button type="submit">提交</button>
    </form>
</body>
</html>
<?php
require_once('config.php');
require_once('smarty/libs/Smarty.class.php');

$smarty = new Smarty();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $gender = $_POST['gender'];
    $age = $_POST['age'];

    // 插入新的数据到数据库中
    $query = "INSERT INTO students (name, gender, age) VALUES ('$name', '$gender', '$age')";
    $result = mysqli_query($conn, $query);

    // 插入成功后,跳转到学生列表页面
    header('Location: students.php');
    exit;
}

$smarty->display('add_student.tpl');

Summary:
Through the introduction of this article, we have learned how to use the Smarty template engine to operate the MySQL database. We can use the Smarty template engine to query the data in the database and display it on the front end, or we can insert user-entered data into the database through the Smarty template engine. This development method that separates back-end logic from front-end display improves the readability and maintainability of the code, and makes it more convenient for us to develop PHP.

The above is the detailed content of Use Smarty template engine to optimize PHP and MySQL development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn