how to insert a row into sql db using pdo in php

To insert a row into an SQL database using PDO in PHP, you can follow these steps:

  1. Create a PDO connection to the database with the necessary credentials.
  2. Prepare an SQL statement with placeholders for the values to be inserted.
  3. Bind the values to the placeholders.
  4. Execute the prepared statement.

Here is the code snippet for doing this:

main.php
// Create a PDO connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Prepare the SQL statement with placeholders
$stmt = $pdo->prepare('INSERT INTO my_table (column1, column2, column3) VALUES (:value1, :value2, :value3)');

// Bind the values to the placeholders
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->bindParam(':value3', $value3);

// Set the values of the variables
$value1 = 'foo';
$value2 = 'bar';
$value3 = 42;

// Execute the prepared statement
$stmt->execute();
575 chars
19 lines

You can replace 'my_database', 'username', and 'password' in the PDO connection line with the actual name of your database and your login credentials. Similarly, you should replace 'my_table' and the column names with the names of your table and columns. Finally, you should set the values of the variables according to the data you want to insert into the database.

related categories

gistlibby LogSnag