To insert data into a database table using PDO in PHP, you need to follow these steps:
$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();
}
$sql = "INSERT INTO your_table_name (column1, column2, column3) VALUES (:value1, :value2, :value3)";
$stmt = $conn->prepare($sql);
$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));
$stmt->execute();
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.