0

My script takes a CSV file containing people's details and inputs them into my mySQL database table using "INSERT INTO table". The primary key of the table is their ID number which is auto-incremented on each insertion.

I will have some PHP after each insertion to make a directory for them on the server. The directory name is their auto generated mySQL ID number.

How could I get their auto-generated ID number after inserting their details in to the database so I can make the directory for each person?

dlofrodloh
  • 1,728
  • 3
  • 23
  • 44

3 Answers3

1

PDO:

$last_id = $db->fetchAll('SELECT LAST_INSERT_ID() as last_id');  
$last_id = intval($last_id[0]['last_id']);

OR

$lastId = $db->lastInsertId();
John Ruddell
  • 25,283
  • 6
  • 57
  • 86
Maximilian Prepl
  • 402
  • 4
  • 10
  • dont answer this question... there is already an exact way to do it (a few minutes after I marked it as a duplicate)... a duplicated question only clutters the community.. its much better to just close the question and if anyone finds this question they will be redirected to the other post... – John Ruddell Oct 13 '14 at 14:24
  • this is a very genious way using SQL to get last id. – Mimouni Oct 13 '14 at 14:34
  • @IlyasMimouni which was already used [HERE](http://stackoverflow.com/questions/10680943/pdo-get-the-last-id-inserted) – John Ruddell Oct 13 '14 at 14:35
  • @JohnRuddell, well, i opened question and went out :D came back and answered. i didn't saw your mark... – Maximilian Prepl Oct 13 '14 at 14:37
  • @IlyasMimouni for pdo i remember just this, for mysqli are more ways... – Maximilian Prepl Oct 13 '14 at 14:37
1

here is a complete example with rollback:

<?php 
try { 
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); 

    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); 

    try { 
        $dbh->beginTransaction(); 
        $tmt->execute( array('user', 'user@example.com')); 
        $dbh->commit(); 
        print $dbh->lastInsertId(); 
    } catch(PDOExecption $e) { 
        $dbh->rollback(); 
        print "Error!: " . $e->getMessage() . "</br>"; 
    } 
} catch( PDOExecption $e ) { 
    print "Error!: " . $e->getMessage() . "</br>"; 
} 
?> 

we use PDO to communicate with database, and to know to last id : $dbh->lastInsertId()

John Ruddell
  • 25,283
  • 6
  • 57
  • 86
Mimouni
  • 3,564
  • 3
  • 28
  • 37
-5

You may use the mysqli_insert_id function.

docs here.

Honesta
  • 1,394
  • 1
  • 11
  • 20