📅  最后修改于: 2023-12-03 15:03:07.818000             🧑  作者: Mango
MySQLi is an extension to the original MySQL library that was developed to provide an enhanced programming interface for accessing and manipulating MySQL databases. In this tutorial, we will discuss how to use MySQLi to insert data into MySQL tables.
Before we proceed with inserting data into MySQL tables, we first need to establish a connection to the database using the mysqli_connect()
function. The function takes four parameters – the database host, username, password, and database name.
// MySQLi connection parameters
$host = "localhost";
$username = "user";
$password = "password";
$database = "my_database";
// Creating a MySQLi database connection
$conn = mysqli_connect($host, $username, $password, $database);
// Checking the MySQLi connection status
if (!$conn) {
die("MySQLi connection failed: " . mysqli_connect_error());
}
To insert data into MySQL tables using MySQLi, we need to use the mysqli_query()
function. The function takes two parameters – the database connection and the SQL statement for inserting data.
// MySQLi insert query
$sql = "INSERT INTO customers (first_name, last_name, email) VALUES ('John', 'Doe', 'johndoe@example.com')";
// Executing the MySQLi query
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully!";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}
In the above code snippet, we're inserting a new record into the customers
table, which has three columns – first_name
, last_name
, and email
. We're providing the values for these columns using the VALUES
keyword in the INSERT
statement.
We can also use MySQLi to insert multiple rows into a MySQL table using a single SQL statement. To do this, we need to provide comma-separated values for each row inside parentheses.
// MySQLi insert query for multiple rows
$sql = "INSERT INTO customers (first_name, last_name, email) VALUES
('John', 'Doe', 'johndoe@example.com'),
('Jane', 'Doe', 'janedoe@example.com'),
('Bob', 'Smith', 'bobsmith@example.com')";
// Executing the MySQLi query
if (mysqli_query($conn, $sql)) {
echo "New records inserted successfully!";
} else {
echo "Error inserting records: " . mysqli_error($conn);
}
In the above code snippet, we're inserting three new rows into the customers
table.
MySQLi provides a convenient and easy-to-use way of inserting data into MySQL tables. In this tutorial, we covered how to connect to a MySQL database using MySQLi and how to insert data into MySQL tables using the mysqli_query()
function. We also discussed how to insert multiple rows using a single SQL statement.