Get the id of the currently inserted ID

When you go to my site, I have a home page with a button: Start enquete. When you click this button, you will see enquete.

Meanwhile, when you pressed this button. An identifier has been added to the database.

Index.php:

        <form method="POST">
            <input type="hidden" name="x">
            <input type="submit" value="Go to enquete">
        </form>
<?php
    if(isset($_POST['x'])){
        $test = $database->insert_user_id();
        //header('Location: enquete/page1.php');
    }

      

And the function:

function insert_user_id(){
        $sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
        $sth = $this->pdo->prepare($sql);
        $sth->execute();
        return $this->pdo->('user_id');
}

      

returns $ this-> pdo -> ('user_id'); this is what i am testing! Now my question. How to get back the last inserted id from a table user.
 I need to show it on the next page. (See // title).

I cannot do this with another request like: SELECT MAX ID

or GetLastInsertId

.
This is because when someone else runs enquete, they will have another error all of a sudden.

How can I let the person store the correct id.

+3


source to share


5 answers


Use PDO :: lastInsertId



$ this-> pdo-> lastInsertId ();

+1


source


Try it. Manual PDO :: lastInsertId



$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

      

+1


source


You can easily do this with the Get method.

But you can also do this by slightly modifying your code.

<form method="POST">
        <input type="hidden" name="x">
        <input type="submit" value="Go to enquete">
    </form>
<?php
if(isset($_POST['x'])){
    $id = $_POST['X'];
    $test = $database->insert_user_id($id);
    //header('Location: enquete/page1.php');
}

      

and change ur function to

function insert_user_id($id){
    $sql = "INSERT INTO user (user_id) VALUES ('".$id. "')";
    $sth = $this->pdo->prepare($sql);
    $sth->execute();
    return $this->pdo->('user_id');
}

      

Edit: I failed.

Check this link http://php.net/manual/en/function.mysql-insert-id.php

0


source


If I understand correctly, you want the row id you just inserted into the database to redirect the user to this?

Index.php

if(isset($_POST['x'])){
    $enqueteId = $database->insert_user_id();
    header('Location: enquete/page1.php?id=' . $enqueteId);
}

      

Functions:

function insert_user_id(){
        $sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
        $sth = $this->pdo->prepare($sql);
        $sth->execute();
        return $this->pdo->lastInsertId();
}

      

0


source


You can use PHP's mysqli_insert_id () function which returns the last inserted table id

For more information follow the link below

http://www.w3schools.com/php/func_mysqli_insert_id.asp

-1


source







All Articles