2

I am trying to insert a Row and get its Primary Key as the Output. However, when I use lastInsertId(), I am always getting False as Output.

Below is the code Snippet. Could you please let me know where I am going Wrong ?

$host        = "host=localhost";
$port        = "port=5432";
$dbname      = "dbname=TestDB";
$credentials = "user=Admin password=Admin";

// Connecting, selecting database
// $dbconn = pg_connect("$host $port $dbname $credentials") or die('Could not connect: ' . pg_last_error());
$conn = new PDO("pgsql:dbname=webdev;host=localhost;port=5432", 'postgres' , 'rameshnr');

// $userName = $_GET['userName'];
// $userComment = $_GET['userComment'];

$userID = 'B101';
$parentComment = 0;
$commentText = 'Test Comment';

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO table_Comments(userID, parentComment, commentText) VALUES (:userID, :parentComment, :commentText)");

$stmt->bindParam(':userID', $userID, PDO::PARAM_STR, 32);
$stmt->bindParam(':parentComment', $parentComment, PDO::PARAM_INT);
$stmt->bindParam(':commentText', $commentText, PDO::PARAM_STR, 500);    


$stmt->execute();

$result= $conn->lastInsertId();

echo "$result";
Prashant Patil
  • 111
  • 1
  • 1
  • 10

1 Answers1

4

The manual states:

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL requires you to specify the name of a sequence object for the name parameter.

You need to pass in the sequence object as the parameter for Postgresql.

PressingOnAlways
  • 11,948
  • 6
  • 32
  • 59