PHP MySQL insert data

PHP MySQL Insert data


Use MySQLi and PDO to insert data into MySQL

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

The following three writing methods can all insert data

INSERT INTO tbl_name VALUES (value1, value2, ...); INSERT INTO tbl_name (column1, column2, ...) VALUES (value1, value2, ...); INSERT INTO tbl_name SET column1 = value1, column2 = value2;

Note: In the first writing method, pay attention to the number. The number of values must be consistent with the number of fields. For example, there are 4 in the table Fields, there must be four values in parentheses; therefore, it is recommended to use the second way of writing

字 字 字 字 字 字:

· PHP in the SQL query statement must be used for quotation marks

#· String values in SQL query statements must be quoted

· Numeric values do not need quotes

· out out‐‐‐‐‐‐‐‐through‐through‐out‐out‐quotes to the INSERT statement. 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 do not need to specify the value in the SQL query statement ; MySQL will automatically add a value to 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(); ?>

Example ( MySQLi - Procedure-oriented)

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

Instance(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; ?>

Continuing Learning
||
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(); ?>
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!