In my site, I have a page to create an site page (addpage.php) and then send the user to a listing of all pages (pages.php), from which they can click on the page they'd like to edit (editp开发者_如何学编程age.php).
I do this because my editpage.php uses the page_id variable to select the page's info from the database and I don't know how to select that variable without first going to pages.php to list all those variables.
I'd like to be able to complete addpage.php and then GO DIRECTLY to editpage.php - but how do I select the page_id that will only just be created on the insert into the database?
My code on addpage.php is basically
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
$id=mysql_insert_id();
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
You can check php manual.
You have to do a query to your database, asking what've been the last inserted id. You can do this running this query:
SELECT LAST_INSERT_ID() as lastId
Then you get the value as you do with any regular query (because this is a regular query actually).
In php there's a function called mysql-insert-id which is more elgant.
Good luck!
If you're using mysql, you can get the ID of the last insert by running the following query SELECT LAST_INSERT_ID()
. This will get you the ID.
精彩评论