Inserting data in PHP

Inserting data in PHP

To insert data into a table in PHP, you can use the following steps:

  1. Establish a database connection using PHP’s mysqli or PDO extension.
  2. 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');
  1. Execute the SQL query using the mysqli_query() or PDO::exec() function, depending on which extension you are using. Here is an example using the mysqli 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');

Get industry recognized certification – Contact us

Menu