How to insert data via PHP MySQL

jacklove
Release: 2023-03-25 14:08:02
Original
2235 people have browsed it

Using MySQLi and PDO to insert data into MySQL

After creating the database and table, we can add data to the table.

The following are some grammar rules:

SQL query statements in PHP must use quotation marks

String values in SQL query statements must be quoted

Numeric values do not require quotes

NULL values do not require quotes

The INSERT INTO statement is usually used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2 , column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, check out our SQL tutorial.

In the previous chapters we have created the table "MyGuests", the table fields are: "id", "firstname", "lastname", "email" and "reg_date". Now, let's start filling the table with data.



Note: If the column is set to AUTO_INCREMENT (such as the "id" column) or TIMESTAMP (such as the "reg_date" column), we will There is no need to specify the value in the SQL query; MySQL automatically adds the value for the column.


The following example adds a new record to the "MyGuests" table:

Example (MySQLi -Object-oriented)

connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "
" . $conn->error; } $conn->close(); ?>
Copy after login

Example (MySQLi - process-oriented)

" . mysqli_error($conn); } mysqli_close($conn); ?>
Copy after login

Example (PDO)

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // 使用 exec() ,没有结果返回 $conn->exec($sql); echo "新记录插入成功"; } catch(PDOException $e) { echo $sql . "
" . $e->getMessage(); } $conn = null; ?>
Copy after login

This article explains in detail the operation of inserting data through php. For more learning materials, please pay attention to php You can watch it on the Chinese website.

Related recommendations:

How to create a MySQL table through PHP

How to create a database through PHP MySQL

PHP knowledge and operations related to connecting to MySQL

The above is the detailed content of How to insert data via PHP MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!