PHP/MySQL insert row then get 'id'

前端 未结 10 920
臣服心动
臣服心动 2020-11-22 16:03

The \'id\' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.

I would do it just as I said it, but is there a way I c

相关标签:
10条回答
  • 2020-11-22 16:25

    The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

    The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

    0 讨论(0)
  • 2020-11-22 16:25

    An example.

        $query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
        $query_new = $databaseConnection->prepare($query_new);
        $query_new->bind_param('s', $_POST['coursename']);
        $query_new->execute();
        $course_id = $query_new->insert_id;
        $query_new->close();
    

    The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row. Hope this helps.

    0 讨论(0)
  • 2020-11-22 16:34

    I just want to add a small detail concerning lastInsertId();

    When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.

    Consider the following example

    $sql = 'INSERT INTO my_table (varNumb,userid) VALUES
         (1, :userid),
         (2, :userid)';
    $sql->addNewNames = $db->prepare($sql);
    addNewNames->execute(array(':userid' => $userid));
    
    echo $db->lastInsertId();
    

    What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.

    The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.

    0 讨论(0)
  • 2020-11-22 16:36

    Try like this you can get the answer:

    <?php
    $con=mysqli_connect("localhost","root","","new");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
    mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
    
    // Print auto-generated id
    echo "New record has id: " . mysqli_insert_id($con);
    
    mysqli_close($con);
    ?>
    

    Have a look at following links:

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

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

    Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0

    0 讨论(0)
  • 2020-11-22 16:38

    Another possible answer will be:

    When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.

    By this method, you don't have to worry about the id, it'll be made automatically.

    For example (taken from w3schools )

    CREATE TABLE Persons
    (
    ID int NOT NULL AUTO_INCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255),
    PRIMARY KEY (ID)
    )
    

    Hope this will be helpful for someone.

    Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

    0 讨论(0)
  • 2020-11-22 16:41

    As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See @Luke's answer for MySQLi). To do this with PDO, proceed as following:

    $db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
    $statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
    $statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
    
    echo $db->lastInsertId();
    
    0 讨论(0)
提交回复
热议问题