Jump to content

Recommended Posts

If your code just inserted something then use mysql_insert_id(). That's just for your code which just did something.

 

If not, and you want to guess at the most recently used value from any query used in any code, you could assume that it's one short of the next auto_increment value. Do a SHOW TABLE STATUS LIKE table and grab the Auto_increment value...

It is working, BUT each time I reload/refresh the browser, the script increments this value. You see, for my assignment, I need other tables to reference this PK as a FK (primary key, foreign key). Is there a simpler/better way to reference a primary key as a foreign key for other tables in same database?

 

//get current Id of some table
function mysql_next_id($table) {
    $result = mysql_query('SHOW TABLE STATUS LIKE "'.$table.'"');
    $rows = mysql_fetch_assoc($result);
    return $rows['Auto_increment'];
}

$someId=mysql_next_id("document")-1;

 

 

I was checking online and came across this useful tidbit:

 

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'

 

My question is how can I take advantage of this query to only output the LAST entered primary key, b/c I want to store that as a foreign key for another table in the same database.

 

Please help a fellow out!

Then you need mysql_insert_id(). Insert the record into the table, get its PK id, then insert into the other tables using the value returned by mysql_insert_id() as the FK for those tables. If it keeps incrementing, you're doing something wrong, like allowing duplicate data insertions.

No, I'm saying each time I reload the script through the browser, it inserts another duplicate record. And also, I WANT to store the last inserted primary key for a given database table b/c I want to pass it as parameter to a function.

 

Any help appreciated, thanks.

That's what I just said. You should code to prevent that from happening by defining UNIQUE indexes on your database table, or at least checking to see if the data already exists before trying to INSERT it. If it's inserting empty records, then you need to prevent the query from running unless the form has been submitted, and contains valid data.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.