Tell me please, there is a code that checks the last id in the table.

<?php $host = 'localhost'; $db = ''; $user = ''; $pass = '; $charset = 'utf8'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, $user, $pass, $opt); $stmt = $pdo->query('SELECT MAX(id) FROM users'); while ($row = $stmt->fetch()) { echo $row['id']; } ?> 

But echo does not output anything. error log displays

PHP Notice: Undefined index: id in / home/fun/test.php on line 17

  • one
    SELECT MAX (id) AS id FROM users. The field must have a name ... - Akina
  • @Akina for sure, thanks. Let's answer. - Vladislav Samokhin
  • Let's answer. Yes, there is no material to answer here ... By the way, in the absence of a name, the field gets a name equal to the expression itself. Those. it was possible to get a value in the initial code using echo $row['MAX(id)']; or echo $row['`MAX(id)`']; (I do not know how correctly in PHP, it is necessary to try ...). - Akina

1 answer 1

 <?php $host = 'localhost'; $db = ''; $user = ''; $pass = '; $charset = 'utf8'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, $user, $pass, $opt); $stmt = $pdo->query('SELECT MAX(id) AS id FROM users'); while ($row = $stmt->fetch()) { echo $row['id']; } ?>