Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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:

<?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 anyone tell what's going wrong? Or another way to achieve that I'm looking to do?

like image 289
user1624005 Avatar asked Sep 21 '12 18:09

user1624005


1 Answers

You're looking for:

$conn->lastInsertId()

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.

like image 50
Alain Tiemblo Avatar answered Oct 21 '22 19:10

Alain Tiemblo