2

I'm gathering data from another page and i'm sending it to process and send the data to my database table. This is the code for that.

require "config.php";

if ( $_POST['insertPost'] == true ){

  $postTitle = $_POST['title'];

  $postContent = $_POST['content'];

  $postImage = $_POST['image'];

  $postDate = $_POST['datetime'];

  $categories = $_POST['categories'];

  $c->query( "INSERT INTO blog ( title, content, image, datetime, categories ) VALUES ( '$postTitle', '$postContent', '$postImage','$postDate', '$categories')" );

  //echo "Inserted";      
}

This is what the table looks like.enter image description here

How can I get the ID info of the inserted data and store it into a variable ?

Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
Ryan Holmes
  • 547
  • 6
  • 14
  • 3
    I am guesing you are using PDO, in this case check out http://php.net/manual/en/pdo.lastinsertid.php – ka_lin Nov 30 '15 at 12:00
  • 1
    I think you are looking for [mysqli_insert_id()](http://php.net/manual/en/mysqli.insert-id.php) – Saty Nov 30 '15 at 12:01
  • Possible duplicate of [How do I get the last inserted ID of a MySQL table in PHP?](http://stackoverflow.com/questions/1685860/how-do-i-get-the-last-inserted-id-of-a-mysql-table-in-php) – Timofey Nov 30 '15 at 12:43

3 Answers3

1

Use mysqli to do DB operation as mysql is deprecated now. So, try this:

$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con, "INSERT INTO blog (title, content, image, datetime, categories) VALUES ('$postTitle', '$postContent', '$postImage','$postDate', '$categories')");

// store auto-generated id
$lastInsertedId = mysqli_insert_id($con);

mysqli_close($con);
prava
  • 3,916
  • 2
  • 24
  • 35
1

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted.

The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

1

Currently I have insufficient reputation to add a comment so can only post an answer. Within my database I have a similar requirement and use:-

sql = "Select Max(idResults) from Results"

idResults being AI (auto increment)

OldSteve
  • 588
  • 1
  • 4
  • 13