How to insert data into a database table using PDO in PHP?

To insert data into a database table using PDO in PHP, you need to follow these steps:

  1. Create a PDO connection to the database:
$dsn = "mysql:host=localhost;dbname=your_database_name"; $username = "your_username"; $password = "your_password"; try { $conn = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
  1. Prepare an SQL INSERT statement:
$sql = "INSERT INTO your_table_name (column1, column2, column3) VALUES (:value1, :value2, :value3)"; $stmt = $conn->prepare($sql);
  1. Bind the values to the parameter placeholders:
$value1 = "value1"; $value2 = "value2"; $value3 = "value3"; $stmt->bindParam(':value1', $value1); $stmt->bindParam(':value2', $value2); $stmt->bindParam(':value3', $value3);

Alternatively, you can directly pass the values through the execute() function:

$stmt->execute(array(':value1' => $value1, ':value2' => $value2, ':value3' => $value3));
  1. Execute the prepared statement to insert the data:
$stmt->execute();
  1. Optionally, you can check if the data was successfully inserted:
if ($stmt->rowCount() > 0) { echo "Data inserted successfully."; } else { echo "Error inserting data."; }

Remember to replace your_database_name, your_username, your_password, your_table_name, column1, column2, column3, value1, value2, and value3 with your own values specific to your database and table.

By following these steps, you can insert data into a database table using PDO in PHP.