Attis
Attis

Reputation: 124

Retrieving last inserted iD then uploading to MySQL. #PDO #PHP

I have a form that uploads Textarea Information and an Image to MySQL simultaneously.

The Textarea iD is AUTO_INCREMENT while the Image iD must be the textarea's copy. I've tried within the $_POST to get lastInsertId(); which returns Fatal error: Call to undefined function lastInsertId().

This is my current code for the isset that uploads the information to the Function and/or query:

if(isset($_POST['update']) && isset($_FILES['photo1'])){
    $update = $_POST['update'];
    $data = $Wall->Insert_Update( $uiD, $update);

    $name       = $_FILES['photo1']['name'];
    $tmp_name   = $_FILES['photo1']['tmp_name'];
    $target = "uploads/". $_FILES['photo1']['name'];

    if (move_uploaded_file($tmp_name,$target)) {
        $sth = $db->prepare("SELECT post_iD FROM posts WHERE uid_fk = :uiD");
        $sth->execute(array(':uiD' => $uiD));

        $post_iD = lastInsertId();
        $sth = $db->prepare('INSERT INTO user_uploads (image_path, uid_fk, image_id_fk) VALUES (:image_path, :uiD, :image_id_fk)');
        $sth->execute(array(':image_path' => $target, ':uiD' => $uiD, ':image_id_fk' => $post_iD));
    }
}

Here is the Insert_Update that is uploading the textarea:

PUBLIC FUNCTION Insert_Update( $uiD, $update){
$sth = $this->db->prepare("SELECT post_iD,message FROM posts WHERE uid_fk = :uiD ORDER by post_iD DESC LIMIT 1");
$sth->execute(array(':uiD' => $uiD));

$result = $sth->fetch();

        if ($update!=$result['message']){

            $sth = $this->db->prepare("INSERT INTO posts ( message, uid_fk, ip, created) VALUES ( :update, :id, :ip, :time)");
            $sth->execute(array(':update' => $update, ':id' => $uiD, ':ip' => $_SERVER['REMOTE_ADDR'], ':time' => time()));

            $sth = $this->db->prepare("
                                        SELECT M.post_iD, M.uid_fk, M.message, M.created, U.username 
                                        FROM Posts M, users U 
                                        WHERE M.uid_fk=U.uiD 
                                        AND M.uid_fk = ? 
                                        ORDER by M.post_iD DESC LIMIT 1");
            $sth->execute(array($uiD));

            $result = $sth->fetchAll();
            return $result;
            } else {
            return false;
        }
}

FORM:

<form method="POST" action="" enctype="multipart/form-data">
    <textarea name="update" id="update" class="_iType"></textarea>
    <input type="file" name="photo1">
    <input type="submit" value="post" class="update_button"> 
</form>

More Information within the database which I doubt it'll be useful.

  1. posts table : where the textarea information will be located.

    *post_iD | message | uid_fk | ip | created |*

  2. user_uploads table : Where the image location will be located.

    *image_iD | image_path | uid_fk | image_id_fk*

NOTICE: image_id_fk should equal post_iD ( which is obvious ).

How is the lastInsertId(); suppose to be used?

EDIT 1: After upload completes the inserted value for the image_id_fk equals 0, instead of the post_iD value. Any ideas for this reason?

Upvotes: 1

Views: 777

Answers (2)

sybear
sybear

Reputation: 7784

It can be used right after you successfully execute an INSERT statement. However, you have to always check whether the execution was successful (or are there affected rows) because there can be last insert ID from previously executed statement.

$sth = $this->db->prepare("INSERT INTO posts ( message, uid_fk, ip, created) VALUES ( :update, :id, :ip, :time)");
$sth->execute(array(':update' => $update, ':id' => $uiD, ':ip' => $_SERVER['REMOTE_ADDR'], ':time' => time()));

$this->db->lastInsertId(); //Upon success, is available

For example: You have a function that creates a new post. This function on success can return the last insert ID value, so you can display that value to user. Like:

if (isset($_GET['id'])){
  $id = $manager->createPost($_GET['id']) ;
  if (is_numeric($id)){
    echo "Your article has been created. ID: {$id}" ; //Or link to it.
  }
}

Update:

Here is my suggestion to your problem: lastInsertId always retuns 0:

Your table, where you insert values, must have PRIMARY KEY AUTO_INCREMENT field, preferrably with type int.

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

You are accessing pdo lastinsertid in wrong way. It requires database connection object.

$post_iD = lastInsertId();

should be

$post_iD = $db->lastInsertId();

Upvotes: 0

Related Questions