0

i have this code where i insert post details to mysql and another function to add photo details to mysql. how can i get the last insert id of the post to insert into the photos table as post_id

function add_img($whichimg,$title)
{
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $sql = "INSERT INTO photos (post_id,title, src) VALUES ('$this->$postid','$title','$whichimg')";
    $add_to_db = $conn->query($sql) or die(mysqli_error());
    return $add_to_db;
}

function add_post($subject,$content)
{
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $sql = "INSERT INTO posts (subject, content) VALUES ('$subject','$content')";
    $add_to_db = $conn->query($sql) or die(mysqli_error());
    $postid=$mysqli->insert_id;

}

add_post is called first.. add_img is called several times afterwards depending on the number of photos

Is there a way to call thi $id in this function onto another ?

SOLVED IT WITH $this->id;

3
  • I don't use mysqli - I've moved from mysql extensions straight to PDO. However, in some old code I have, I find the following immediately following an insert query. $threadId = mysql_insert_id(); Commented Aug 21, 2013 at 23:34
  • Thanks. the problem for me is to get that $threadID to be inserted into the other table. how can i call it in another function .. im assuming something like this->threadID .. ddnt work though Commented Aug 21, 2013 at 23:38
  • A pleasure. I'm guessing that the 2nd function is called first. In that case, simply return the value that mysql_insert_id gives you. Then, as Sasanka Panguluri has suggested, use that return value as one of the parameters for add_img. I.e add_img($whichimg, $title, $postId) Commented Aug 21, 2013 at 23:42

1 Answer 1

1

Accept another argument for function add_img($whichimg,$title)

As

   function add_img($whichimg,$title,$postid)

Since your add_img needs $postid, you should return it from add_post($subject,$content) Inside the function, Instead of $postid=$mysqli->insert_id; , just say return $mysqli->insert_id;

Finally, When you call these methods, make sure you do this:

$id = add_post(<...>,<...>);
add_img(<...>,<...>,$id);
Sign up to request clarification or add additional context in comments.

2 Comments

hi. THANKS.. i am now able to get the insert id.. im having trouble getting that and using it in another function.. As my the posts and photos are handled in differnt functions
i inserted a part of the code block on to the description if it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.