Inserting Data into a MySQL Database using PHP
In this tutorial, we will learn how to insert data into a MySQL database using PHP. We will be using the mysqli extension, which is a more improved version of the mysql extension.
Prerequisites
Before we start, you will need the following:
- A MySQL database
- A PHP development environment
- The mysqli extension installed
Creating a MySQL Database
If you do not already have a MySQL database, you can create one by following these steps:
- Log in to your MySQL server using the following command:
- Create a new database using the following command:
- Select the newly created database using the following command:
mysql -u root -p
CREATE DATABASE database_name;
USE database_name;
Creating a Table
Next, we need to create a table to store our data. We can do this using the following command:
CREATE TABLE table_name (
column_name1 data_type,
column_name2 data_type,
...
);
For example, to create a table to store user data, we can use the following command:
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
Inserting Data
Now that we have created a table, we can insert data into it using the following syntax:
INSERT INTO table_name (column_name1, column_name2, ...)
VALUES (value1, value2, ...);
For example, to insert a new user into the users table, we can use the following command:
INSERT INTO users (username, password, email)
VALUES ('john', 'doe', 'john@example.com');
mysqli_query() Function
The mysqli_query() function is used to execute SQL queries on a MySQL database. The function takes two parameters:
- The MySQL connection
- The SQL query to execute
The function returns a boolean value indicating whether the query was executed successfully.
Example
Here is an example of how to insert data into a MySQL database using PHP:
connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
// Prepare the SQL query
$sql = "INSERT INTO users (username, password, email)
VALUES (?, ?, ?)";
// Prepare the statement
$stmt = $mysqli->prepare($sql);
// Bind the parameters
$stmt->bind_param('sss', $username, $password, $email);
// Set the parameter values
$username = 'john';
$password = 'doe';
$email = 'john@example.com';
// Execute the statement
$stmt->execute();
// Close the statement
$stmt->close();
// Close the connection
$mysqli->close();
?>
Conclusion
In this tutorial, we learned how to insert data into a MySQL database using PHP. We covered the following topics:
- Creating a MySQL database
- Creating a table
- Inserting data using the mysqli_query() function
I hope this tutorial has been helpful. If you have any questions, please feel free to leave a comment below.