recall id after adding a query to MySQL database

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jochem

    recall id after adding a query to MySQL database

    Hello,

    Lately I came accross this problem a couple of times, and I know there
    must be a clever solution. However, I did not find it untill now.

    When I add a entry to my mysql database from a PHP form, it gives the
    document an 'id number', which is generated by MySQL. In my PHP script
    I would like to continue with id, since that is easier. At the moment
    I place a SELECT query in which I basically match the values I still
    have in my PHP_POST with the values in the database (those I just
    entered).

    I have the feeling that there is a simple code for replacing those
    lines of PHP script and unnecessary queries. Is there somebody who can
    help me, please?

    Jochem
  • Senator Jay Billington Bulworth

    #2
    Re: recall id after adding a query to MySQL database

    In article <2e2e0791.03122 40457.1ef57d08@ posting.google. com>,
    jdonkers@operam ail.com (Jochem) wrote:
    [color=blue]
    > Hello,
    >
    > Lately I came accross this problem a couple of times, and I know there
    > must be a clever solution. However, I did not find it untill now.
    >
    > When I add a entry to my mysql database from a PHP form, it gives the
    > document an 'id number', which is generated by MySQL. In my PHP script
    > I would like to continue with id, since that is easier. At the moment
    > I place a SELECT query in which I basically match the values I still
    > have in my PHP_POST with the values in the database (those I just
    > entered).
    >
    > I have the feeling that there is a simple code for replacing those
    > lines of PHP script and unnecessary queries. Is there somebody who can
    > help me, please?[/color]

    Assuming the document ID number is the result of a MySQL auto_increment
    field,

    $result = mysql_query('IN SERT INTO foo SET bar=1', $db);
    $id = mysql_insert_id ();
    <http://php.net/mysql_insert_id >

    or

    $result = mysql_query('IN SERT INTO foo SET bar=1', $db);
    $result = mysql_query('SE LECT LAST_INSERT_ID( ) AS id', $db);
    $myrow = mysql_fetch_arr ay($result);
    $id = $myrow[id];

    The mysql_insert_id () function will return the numeric value of the
    auto_increment field of the last inserted record. The MySQL query for
    LAST_INSERT_ID( ) will return the same.

    Happy Holidays!

    hth

    --
    Bulworth : funha@fung.arg | My email address is ROT13 encoded, decode to mail
    --------------------------|--------------------------------------------------
    <http://www.phplabs.com/> | PHP scripts and thousands of webmaster resources!

    Comment

    • Jochem

      #3
      Re: recall id after adding a query to MySQL database

      Thanks that was my missing link!

      Comment

      Working...