last_insert _id inserts null in php for loop code example

Example 1: get id of record created php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example 2: php pdo get id selected by href

<?php
include "/includes/db.php";
$id = $_GET['id'];
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,        // enable PDO errors
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,   // fetch associative arrays by default
    PDO::ATTR_EMULATE_PREPARES => false,                // Use native prepared statements
];
//                      You should always specify charset VVVVV
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, $options);

// Prepare and execute SQL passing in the value of $id  // Verificar o pedido "GET" id param
  $id = $_GET['id'];
  
  // Preparar e executar a passagem SQL no valor de $id
  $query = $pdo->prepare('SELECT * FROM nametable WHERE id = ? ORDER BY nameselect DESC');
  $query->execute([$id]);
?>
  <html>
   <?php foreach($query as $row ?>
     $row  ['namerow']
     <?php } ?>
  </html>

Tags:

Php Example