Fetch Data from MySQL (mysqli Procedural)
Fetches rows from MySQL with procedural `mysqli_*`, a prepared `SELECT`, explicit bind/result checks, and an array result for rendering.
Purpose
Fetches rows from MySQL with procedural `mysqli_*`, a prepared `SELECT`, explicit bind/result checks, and an array result for rendering.
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 Data from MySQL (mysqli Procedural).
*
* Purpose:
* Reads published records from a table with a procedural mysqli prepared
* statement and returns rows as arrays.
*
* @param mysqli $connection Open procedural mysqli connection.
* @param string $item_type Item type filter.
* @param int $limit Maximum rows to return.
* @return array Success flag, rows, and public message.
*/
function ogSnippetFetchDataMysqliProcedural(mysqli $connection, string $item_type, int $limit): array {
$item_type = trim($item_type);
if ($item_type === '') {
return array('success' => false, 'rows' => array(), 'message' => 'Item type is required.');
}
if ($limit < 1) {
$limit = 10;
}
if ($limit > 50) {
$limit = 50;
}
$sql = 'SELECT id, title, slug FROM items WHERE item_type = ? AND is_published = 1 ORDER BY title ASC LIMIT ?';
$statement = mysqli_prepare($connection, $sql);
if ($statement === false) {
return array('success' => false, 'rows' => array(), 'message' => 'Query preparation failed.');
}
mysqli_stmt_bind_param($statement, 'si', $item_type, $limit);
$executed = mysqli_stmt_execute($statement);
if ($executed === false) {
mysqli_stmt_close($statement);
return array('success' => false, 'rows' => array(), 'message' => 'Query execution failed.');
}
mysqli_stmt_bind_result($statement, $id, $title, $slug);
$rows = array();
while (mysqli_stmt_fetch($statement)) {
$rows[] = array(
'id' => (int) $id,
'title' => $title,
'slug' => $slug
);
}
mysqli_stmt_close($statement);
return array(
'success' => true,
'rows' => $rows,
'message' => 'Rows fetched with procedural mysqli.'
);
}
/*
$result = ogSnippetFetchDataMysqliProcedural($connection, 'snippet', 12);
foreach ($result['rows'] as $library_row) {
echo htmlspecialchars($library_row['title'], ENT_QUOTES, 'UTF-8')."
";
}
*/