📅  最后修改于: 2023-12-03 15:03:35.400000             🧑  作者: Mango
When working with a database, inserting data is one of the most important operations. In this guide, we'll learn how to insert data into a MySQL database using PHP.
Before we begin, make sure you have the following:
To insert data into a MySQL database, we first need to establish a connection to the database. We can use the mysqli_connect()
function in PHP to connect to the database. Here's an example:
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In the above example, replace yourusername
, yourpassword
, and yourdatabasename
with your actual database credentials.
To insert data into a MySQL database using PHP, we can use the mysqli_query()
function. Here's an example:
$sql = "INSERT INTO users (name, email, phone) VALUES ('John Doe', 'john@example.com', '555-555-5555')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
In the above example, we're inserting a new record into the users
table with the name, email, and phone values. The mysqli_query()
function executes the SQL statement, and we check the result to see if the record was inserted successfully.
Instead of hard-coding the insert data values, we can use PHP variables to insert data dynamically. Here's an example:
$name = "Jane Doe";
$email = "jane@example.com";
$phone = "555-555-5555";
$sql = "INSERT INTO users (name, email, phone) VALUES ('$name', '$email', '$phone')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
In the above example, we're inserting a new record into the users
table with dynamic values based on the variable values.
In this guide, we learned how to insert data into a MySQL database using PHP. We covered the basics of connecting to the database, inserting data, and inserting data dynamically using variables. Now you can start inserting data into your own MySQL databases using PHP.