Skip to content
← Back to Snippets
Code

Fetch One Row from MySQL with Procedural mysqli

Fetches one published MySQL row by slug with a procedural mysqli prepared statement and returns a structured result for controller display logic.

Purpose

Fetches one published MySQL row by slug with a procedural mysqli prepared statement and returns a structured result for controller display logic.

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


/**
 * Fetch One Row from MySQL with Procedural mysqli.
 *
 * Purpose:
 * Fetches one published library row by slug using a procedural mysqli prepared
 * statement and returns a structured result for controller display logic.
 *
 * @param mysqli $connection Open procedural mysqli connection.
 * @param string $slug Library item slug to fetch.
 * @return array Success flag, row data, and public message.
 */
function ogSnippetFetchOneRowProceduralMysqli(mysqli $connection, string $slug): array {
	$slug = trim($slug);

	if ($slug === '') {
		return array(
			'success' => false,
			'row' => array(),
			'message' => 'Slug is required before a row can be fetched.'
		);
	}

	$sql = 'SELECT id, title, slug FROM items WHERE slug = ? AND is_published = 1 LIMIT 1';
	$statement = mysqli_prepare($connection, $sql);

	if ($statement === false) {
		return array(
			'success' => false,
			'row' => array(),
			'message' => 'Query preparation failed.'
		);
	}

	mysqli_stmt_bind_param($statement, 's', $slug);
	$executed = mysqli_stmt_execute($statement);

	if ($executed === false) {
		mysqli_stmt_close($statement);

		return array(
			'success' => false,
			'row' => array(),
			'message' => 'Query execution failed.'
		);
	}

	mysqli_stmt_bind_result($statement, $id, $title, $matched_slug);
	$row = array();

	if (mysqli_stmt_fetch($statement)) {
		$row = array(
			'id' => (int) $id,
			'title' => $title,
			'slug' => $matched_slug
		);
	}

	mysqli_stmt_close($statement);

	if (empty($row)) {
		return array(
			'success' => false,
			'row' => array(),
			'message' => 'No published row matched that slug.'
		);
	}

	return array(
		'success' => true,
		'row' => $row,
		'message' => 'One row fetched with procedural mysqli.'
	);
}

/*
$result = ogSnippetFetchOneRowProceduralMysqli($connection, 'rocinante-flight-log');
if ($result['success'] === true) {
	echo htmlspecialchars($result['row']['title'], ENT_QUOTES, 'UTF-8');
}
*/