I need to generate a link to the current game, I didn’t think of anything better how to use lastInsertId , I ’m writing to OOP, and it turns out that the result of executing the code eventually displays 0 instead of the last id

class CheckStart extends Db { public $data; public function __construct() { $this->data = $_POST; } public function checkStart() { if ( isset($this->data['do_start']) ) { $hp_default = 1000; // Стандартное количество хп $sql = $this->connect()->prepare("INSERT INTO `game` (`hp`) VALUES (:hp)"); $sql->bindParam(":hp", $hp_default, PDO::PARAM_INT); $sql->execute(); echo "success"; // header("Location: index.php"); } else { echo "fail"; } } public function generateLink() { // Генерирования ссылки на игру $sql = $this->connect()->query("SELECT `id` FROM `game`"); $sql = $sql->fetch(PDO::FETCH_ASSOC); $sql = $this->connect()->lastInsertId(); echo $sql; } } $start = new CheckStart; $start->checkStart(); $start->generateLink();` 
  • Not an expert, but you have a sequence of queries like this: INSERT -> SELECT -> lastInsertId() . It is not right. lastInsertId() must be after INSERT a. Why do you need this SELECT ? try deleting the first 2 lines from lastInsertId() - Manitikyl
  • @Manitikyl I thought this sequence was correct, first adding, and then outputting already updated information from the database. But nevertheless, I did everything as you said, the result did not change, still prints 0 public function generateLink() { // Генерирования ссылки на игру $sql = $this->connect()->lastInsertId(); echo $sql; } public function generateLink() { // Генерирования ссылки на игру $sql = $this->connect()->lastInsertId(); echo $sql; } public function generateLink() { // Генерирования ссылки на игру $sql = $this->connect()->lastInsertId(); echo $sql; } - Ulquiorra Siffer
  • When you do an INSERT , the answer immediately comes and is written to lastInsertId . And with your SELECT you are likely to reset it. - Manitikyl
  • Modify for test: echo "success"; on echo $this->connect()->lastInsertId(); . If it is 0 again, then we will think. - Manitikyl
  • @Manitikyl Changed, but again 0 - Ulkiorra Sifer

0