PHP MySQL: Insert Data Into a Table
Inserting data into a MySQL database using PHP involves executing an SQL INSERT INTO
statement. This allows you to add new records to a specified table.
Syntax for SQL INSERT
table_name
: The name of the table where data will be inserted.column1, column2, ...
: The columns in which the values will be inserted.value1, value2, ...
: The corresponding values to insert.
Code Example: Insert Data
1. Establish a Database Connection
2. Execute an SQL INSERT INTO
Query
Insert a new record into the users
table:
Using Prepared Statements
Prepared statements are more secure and protect against SQL injection, especially when inserting user inputs.
Insert Multiple Records
You can insert multiple records in a single query by separating each set of values with a comma:
Fetch the Last Inserted ID
To retrieve the ID of the last inserted record (for tables with an AUTO_INCREMENT
column):
Complete Example
Key Notes
- Escape User Input: Use prepared statements or
mysqli_real_escape_string
to prevent SQL injection. - Handle Errors: Always handle errors to debug issues effectively.
- Check for Required Fields: Ensure all required columns have values to avoid SQL errors.
- Use AUTO_INCREMENT: Use an
AUTO_INCREMENT
column for unique IDs if needed. - Backup Data: Regularly back up your database to avoid data loss during updates.
Let me know if you need more examples or advanced usage!