Search code examples
phpauto-increment

Display MySQL auto-increment key in App Inventor


I'm currently developing an app for project work. So, after submitting data to MySQL table, how can I setup PHP to display the auto-increment key (confirmation code) of the table for each results submitted? I already have the PHP code for submitting data. I need the code for getting the auto-increment key. Thanks in advance.


Solution

  • There are a number of ways to do this depending on what mysql libraries or statements you use in your PHP.

    example 1: Perform another query (Not so efficient but works)

    SELECT MAX(id) FROM table
    

    This will return the highest value in your table (ie the last inserted id)

    +1 would give you the next in line AutoIncrement

    example 2:

    Assuming you use default mysql_query in PHP, while the connection is open you can use this:

    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    
    if (!$link) {
    
        die('Could not connect: ' . mysql_error());
    
    }
    
    mysql_select_db('mydb');
    
    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    
    printf("Last inserted record has id %d\n", mysql_insert_id());
    

    Whereas mysql_insert_id() will return the actual inserted id for your query.

    Hope this helps