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

I am inserting, using PDO, a row into a table, and I need a new row id, so I can redirect to a new page based on 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 php throws an error:

 <?php $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)'); $stmt->execute(array( 'link' => 'fake', 'title' => $title, 'caption' => $caption )); $id = PDO::lastInsertId(); header("Location: localhost/image?id=$id"); 

Can anybody say what goes wrong? Or another way to achieve what I'm looking for?

+7
source share
2 answers

You are looking for:

 $conn->lastInsertId() 

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

+10
source

You should not call it directly from the class. I suggest you review OOP again.

You have created an instance of the PDO class in the $conn variable, and you must call the function from the object you created.

$conn->lastInsertId()

+3
source

All Articles