Char
Char

Reputation: 318

Creating a new ID using mysqli_insert_id and storing in session

This was working fine before and now it's not. I'll try explain the problem best I can.

I am creating a website where people post ads for horses they are trying to sell, or put on loan - people can also post if they are looking for a specific horse. I am using this code to create a new ID once an advert has been posted, because once the ad is posted, it takes them to a page where they can upload a picture. This part of my code isn't working.

        if ($conn->query($sql)) {

        // echo "New Record has id ".$conn->mysqli_insert_id;

        $_SESSION['hid'] = $conn->mysqli_insert_id;

$conn is the variable I use when connecting to the DB so no problem there. No ID is being generated but yesterday it was fine and nothing changed since then. Any tips or anything I could be doing wrong?

Upvotes: 0

Views: 166

Answers (1)

Saty
Saty

Reputation: 22532

You have created an object for your connection in $conn variable. This means that you are taking the object oriented approach versus the procedural approach. You then used mysqli_insert_id which is a procedural function.

You have two options:

1. Object Oriented Approach
use insert_id as a property of $conn.

$_SESSION['hid'] = $conn->insert_id;

2. Procedural Approach
use the procedural function mysqli_insert_id if no object was created.

mysqli_insert_id($conn); 

Read manual mysqli_insert_id

More Info: Object-Oriented Programming vs. Procedural Programming

Upvotes: 1

Related Questions