Home » Php » Fatal error: Non-static method in PHP using PDO for MySQL

Fatal error: Non-static method in PHP using PDO for MySQL

Posted by: admin July 12, 2020 Leave a comment


I’m inserting, using PDO, a row into the table, and I need the id of the new row so I can redirect to the new page based off that row.

When I use

$id = PDO::lastInsertId();

I get

Fatal error: Non-static method PDO::lastInsertId() cannot be called statically in C:\xampp\htdocs\createimage.php on line 16

Here’s the php that results in an error:


$title = $_POST['title'];
$caption = $_POST['caption'];

$conn = new PDO('mysql:host=localhost;dbname=imagesite', 'root', '');

$stmt = $conn->prepare('INSERT INTO images (id,link,title,caption) VALUES (NULL,:link,:title,:caption)');

    'link' => 'fake',
    'title' => $title,
    'caption' => $caption

$id = PDO::lastInsertId();

header("Location: localhost/image?id=$id");

Can anyone tell what’s going wrong? Or another way to achieve that I’m looking to do?

How to&Answers:

You’re looking for:


In the PHP documentation, they show you PDO::lastInsertId() but that’s to understand this method is within the PDO class. But you need to call it using your object.


You shouldn’t call it directly from the class.. I suggest you to review the OOP once more..

you have created an instance of the PDO class in the $conn variable and you should call the function from the object you have made..