-2

On my XAMPP server I have a database table on phpMyAdmin. In that table, I have a few columns, and one of them is id column (Integer).

I want to get the latest added item's ID, increment it by one and then assign it to a new item that the function adds to the table.

The problem is that whenever there is a new item, it is automatically assigned with 1 as id, nothing above 1.

$sql = "SELECT * FROM items";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        if( $_SESSION["increment"] == "yes"){
            $_SESSION["id"] = $row["id"];
        }else
            $_SESSION["id"]=$_SESSION["id"]+1;
    }
} else {
    $_SESSION["id"] = 1;
}
Ido
  • 171
  • 2
  • 13

3 Answers3

0

It seems to me that you need well known AUTO_INCREMENT functionality built inside MySQL database. Just define in your database schema for your table that column is AUTO_INCREMENT column type, and it will be automatically incremented by 1 upon each new insert into table.

sbrbot
  • 6,169
  • 6
  • 43
  • 74
0

This will give you last increment Id.

 $sql = "SELECT id FROM items order by id DESC LIMIT 0,1";

Then you dont want have a while loop to find last increment Id.

mugzi
  • 809
  • 4
  • 16
  • 33
0

error reporting said what? and mysqli_error($conn)?

-- Fred-ii-

  • The above request by Fred -ii- sums it up, if your ->num_rows is returning zero or not a number (false) then you have an SQL error, so you need to check your error logs, and check your database connection.

  • Have you started your session with session_start?

  • Do you intend that the first else calls without brackets, only executing the single following line, $_SESSION["id"]=$_SESSION["id"]+1; ?

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132