Skip to content
← Back to Snippets
Code

Get Last Insert ID

Inserts one mission-log row with procedural mysqli, then returns the exact auto-increment ID produced by that insert.

Purpose

Inserts one mission-log row with procedural mysqli, then returns the exact auto-increment ID produced by that insert.

Snippet details

ContextDatabaseLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Get Last Insert ID.
 *
 * Purpose:
 * Inserts a single row with a prepared procedural mysqli statement and returns
 * the auto-increment ID from that same connection.
 *
 * @param mysqli $connection Open mysqli connection.
 * @param string $ship_name Ship or crew reference to store.
 * @param string $mission_note Short mission note.
 * @return array Insert status, inserted ID, and public message.
 */
function ogSnippetGetLastInsertId(mysqli $connection, string $ship_name, string $mission_note): array {
	$ship_name = trim($ship_name);
	$mission_note = trim($mission_note);

	if ($ship_name === '' || $mission_note === '') {
		return array(
			'success' => false,
			'insert_id' => 0,
			'message' => 'Ship name and mission note are required.'
		);
	}

	$sql = 'INSERT INTO mission_logs (ship_name, mission_note, created_at) VALUES (?, ?, NOW())';
	$statement = mysqli_prepare($connection, $sql);

	if ($statement === false) {
		return array(
			'success' => false,
			'insert_id' => 0,
			'message' => 'Mission log insert could not be prepared.'
		);
	}

	mysqli_stmt_bind_param($statement, 'ss', $ship_name, $mission_note);
	$executed = mysqli_stmt_execute($statement);

	if ($executed === false) {
		mysqli_stmt_close($statement);
		return array(
			'success' => false,
			'insert_id' => 0,
			'message' => 'Mission log insert failed.'
		);
	}

	$insert_id = (int) mysqli_insert_id($connection);
	mysqli_stmt_close($statement);

	return array(
		'success' => true,
		'insert_id' => $insert_id,
		'message' => 'Mission log stored with ID '.$insert_id.'.'
	);
}

/*
$result = ogSnippetGetLastInsertId($connection, 'Rocinante', 'Epstein drive diagnostic completed.');
print_r($result);
*/