Home  >  Article  >  Backend Development  >  How to insert data into a MySQL table using PHP?

How to insert data into a MySQL table using PHP?

WBOY
WBOYOriginal
2024-06-02 14:26:56589browse

How to insert data into a MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to insert. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

如何使用 PHP 插入数据到 MySQL 表中?

How to insert data into a MySQL table in PHP

Inserting data into a MySQL table is a common task in PHP . This article will guide you step-by-step through doing this using PHP.

Prerequisites:

  • PHP 7.x or higher
  • MySQL database
  • MySQL connection information ( Server name, username, password, database name)

Step 1: Connect to the database

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database_name";

// 创建一个连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
?>

Step 2: Prepare SQL query

$sql = "INSERT INTO table_name (column1, column2, column3) VALUES (value1, value2, value3)";

Step 3: Execute query

if ($conn->query($sql) === TRUE) {
    echo "新记录已成功插入。";
} else {
    echo "插入数据时出错:" . $conn->error;
}
?>

Practical case

Suppose you have a user named "users" MySQL table with the following columns:

  • user_id (primary key)
  • first_name
  • last_name

Now, let’s insert using PHP A new record.

$user_id = 1;
$first_name = "John";
$last_name = "Smith";

$sql = "INSERT INTO users (user_id, first_name, last_name) VALUES ($user_id, '$first_name', '$last_name')";

if ($conn->query($sql) === TRUE) {
    echo "新用户已成功插入。";
} else {
    echo "插入数据时出错:" . $conn->error;
}
?>

Close the connection

Finally, it is very important to close the MySQL connection.

$conn->close();
?>

The above is the detailed content of How to insert data into a MySQL table using PHP?. 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