insert into sql with prepared statment with bindparam in php

To insert data into a SQL database using prepared statements with bindParam in PHP, follow the steps below:

  1. Connect to the Database: You have to first establish a connection to your SQL database.
main.php
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
80 chars
2 lines
  1. Create the Insert Query: Create the insert query for inserting data into the database.
main.php
$sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
76 chars
2 lines
  1. Prepare the Query: Prepare the query using the prepare() method of the PDO object.
main.php
$stmt = $conn->prepare($sql);
30 chars
2 lines
  1. Bind the Query Parameters: Bind the parameters to the query using the bindParam() method.
main.php
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':age', $age);
102 chars
4 lines
  1. Execute the Query: Execute the query using the execute() method.
main.php
$stmt->execute();
18 chars
2 lines
  1. Close the Connection: Close the connection to the database.
main.php
$conn = null;
14 chars
2 lines

Example:

main.php
// connect to database
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// prepare sql statement
$sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
$stmt = $conn->prepare($sql);

// bind parameters
$name = "John Doe";
$email = "johndoe@example.com";
$age = 30;
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':age', $age);

// execute statement
$stmt->execute();

// close the connection
$conn = null;
499 chars
21 lines

gistlibby LogSnag