Skip to content
← Back to Snippets
Code

Delete Data from MySQL

Deletes one confirmed row with procedural mysqli and returns a clear result without unsafe broad deletion.

Purpose

Deletes one confirmed row with procedural mysqli and returns a clear result without unsafe broad deletion.

Snippet details

ContextDatabaseLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Database Integrity

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.
 */

/**
 * Delete Data from MySQL.
 *
 * Purpose:
 * Deletes one confirmed row with a prepared procedural mysqli statement.
 *
 * @param mysqli $connection Open mysqli connection.
 * @param int $cargo_id Cargo row ID to delete.
 * @param string $confirmation_code User confirmation code for the delete action.
 * @return array Delete status and affected-row count.
 */
function ogSnippetDeleteDataMysql(mysqli $connection, int $cargo_id, string $confirmation_code): array {
	$confirmation_code = trim($confirmation_code);

	if ($cargo_id < 1) {
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Cargo ID is invalid.');
	}

	if ($confirmation_code !== 'CONFIRM-DELETE') {
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Delete confirmation was not accepted.');
	}

	$sql = 'DELETE FROM cargo_manifest WHERE id = ? LIMIT 1';
	$statement = mysqli_prepare($connection, $sql);

	if ($statement === false) {
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Cargo delete could not be prepared.');
	}

	mysqli_stmt_bind_param($statement, 'i', $cargo_id);
	$executed = mysqli_stmt_execute($statement);

	if ($executed === false) {
		mysqli_stmt_close($statement);
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Cargo delete failed.');
	}

	$affected_rows = mysqli_stmt_affected_rows($statement);
	mysqli_stmt_close($statement);

	if ($affected_rows < 1) {
		return array('success' => true, 'affected_rows' => 0, 'message' => 'No cargo row was deleted.');
	}

	return array('success' => true, 'affected_rows' => $affected_rows, 'message' => 'Cargo row deleted.');
}

/*
$result = ogSnippetDeleteDataMysql($connection, 12, 'CONFIRM-DELETE');
print_r($result);
*/