Category: php

Php function to load table into a hash

February 24th, 2021 — 10:51am

Here’s a function I use to load mysql data into a hash for quick lookups in my code:

function select_sql_hash ($link,$sql,&$all_hash,$key) {
  $r = mysqli_query($link,$sql);
  if (!$r) {
   $message  = 'Invalid query: ' . mysqli_error() . "\n";
   $message .= 'Whole query: ' . $sql;
   print "$message\n";
  while ($results = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
        $all_hash[$results[$key]] = $results;
This can be called something like this:
$topics = array();
select_sql_hash($db,"select topicid,name,created_date from topic",$topics,"topicid");
The results is a hashed array where $topic[5][‘name’] is the “name” field for that topic, and $topic[5][‘created_date’] is the date created, etc. This is handy if the code is doing some mapping to print out topic names and you’d like to avoid joining the tables. Or it may save additional queries to the database when displaying data.

Comments Off on Php function to load table into a hash | php

Back to top