Skip to content
← Back to Snippets
Code

Update Data in MySQL

Updates one inventory row with procedural mysqli, validates the row ID, and reports whether a row actually changed.

Purpose

Updates one inventory row with procedural mysqli, validates the row ID, and reports whether a row actually changed.

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

/**
 * Update Data in MySQL.
 *
 * Purpose:
 * Updates one row with a prepared procedural mysqli statement and returns a
 * useful affected-row result without exposing database errors to the browser.
 *
 * @param mysqli $connection Open mysqli connection.
 * @param int $inventory_id Inventory row ID to update.
 * @param string $status New inventory status.
 * @param int $quantity New quantity value.
 * @return array Update status and affected-row count.
 */
function ogSnippetUpdateDataMysql(mysqli $connection, int $inventory_id, string $status, int $quantity): array {
	$status = trim($status);

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

	if ($status === '') {
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Inventory status is required.');
	}

	if ($quantity < 0) {
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Quantity cannot be negative.');
	}

	$sql = 'UPDATE ship_inventory SET status = ?, quantity = ?, updated_at = NOW() WHERE id = ? LIMIT 1';
	$statement = mysqli_prepare($connection, $sql);

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

	mysqli_stmt_bind_param($statement, 'sii', $status, $quantity, $inventory_id);
	$executed = mysqli_stmt_execute($statement);

	if ($executed === false) {
		mysqli_stmt_close($statement);
		return array('success' => false, 'affected_rows' => 0, 'message' => 'Inventory update 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 inventory row changed.');
	}

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

/*
$result = ogSnippetUpdateDataMysql($connection, 7, 'Firefly cargo locked', 42);
print_r($result);
*/