Inserting data in PHP
To insert data into a table in PHP, you can use the following steps:
- Establish a database connection using PHP’s
mysqli
orPDO
extension. - Define a SQL query that inserts data into the table. For example, the following code inserts a new user into the “users” table:
INSERT INTO users (username, password) VALUES ('john', 'password123');
- Execute the SQL query using the
mysqli_query()
orPDO::exec()
function, depending on which extension you are using. Here is an example using themysqli
extension:
bashCopy code$conn = mysqli_connect("localhost", "username", "password", "database_name");
$sql = "INSERT INTO users (username, password) VALUES ('john', 'password123')";
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully.";
} else {
echo "Error inserting data: " . mysqli_error($conn);
}
Note that you should always sanitize user input and use prepared statements to prevent SQL injection attacks. Also, if you need to insert multiple rows at once, you can use the INSERT INTO
statement with multiple value sets separated by commas, like this:
sqlCopy codeINSERT INTO users (username, password)
VALUES
('john', 'password123'),
('jane', 'password456'),
('bob', 'password789');