Home > Article > Backend Development > Interaction of PHP functions with MySQL database
PHP has the function of connecting, querying and operating MySQL database. Commonly used PHP functions include: mysqli() for connecting to the database, query() for executing queries, and prepare() for preparing insert statements. In a practical case, you can use PHP functions to create a user registration system, including creating database tables, collecting user input, connecting to the database, preparing insert statements, performing insert operations and redirecting users.
Interaction of PHP functions with MySQL database
PHP is a server-side scripting language that has a wide range of functions, including The ability to interact with the MySQL database. This article will introduce commonly used PHP functions to connect, query and operate MySQL database, and provide a practical case.
Connect to database
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbName = "database_name"; // 创建一个 mysqli 对象 $conn = new mysqli($servername, $username, $password, $dbName); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } ?>
Execute query
<?php // 准备查询语句 $sql = "SELECT * FROM table_name"; // 执行查询并存储结果 $result = $conn->query($sql); // 遍历结果集 while ($row = $result->fetch_assoc()) { echo $row["column_name"] . "<br>"; } ?>
Insert data
<?php // 准备插入语句 $sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')"; // 执行插入操作 if ($conn->query($sql) === TRUE) { echo "记录已成功插入"; } else { echo "插入记录失败: " . $conn->error; } ?>
Practical case: Create a user registration system
The following is a simple practical case that uses PHP functions to interact with the MySQL database to create a user registration system:
users
, containing id
, username
, password
and email
field. Code example:
HTML form:
<form action="register.php" method="post"> <label for="username">用户名:</label><input type="text" name="username"><br> <label for="password">密码:</label><input type="password" name="password"><br> <label for="email">电子邮件:</label><input type="email" name="email"><br> <input type="submit" value="注册"> </form>
register.php script:
<?php // 连接到数据库 include 'connect_db.php'; // 准备插入语句 $sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)"; // 绑定用户输入的值 $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $username, $password, $email); // 设置用户输入的值 $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $email = $_POST['email']; // 执行插入操作 $stmt->execute(); // 关闭语句对象 $stmt->close(); // 重定向到成功页面 header('Location: success.php'); ?>
The above is the detailed content of Interaction of PHP functions with MySQL database. For more information, please follow other related articles on the PHP Chinese website!