tags:

views:

26

answers:

1

I am trying to create a look-up table from the results which mysql_fetch_assoc returns, and this is the code I have so far:

protected function dumpResultAsHash($primaryKey)
{
    if (empty($primaryKey) || !isset($primaryKey))
        throw new Exception("Primary key cannot be null or not defined!");

    $resultset = array();

    while ($result = mysql_fetch_assoc($this->m_result))
        $resultset[$result[$primaryKey]] =$result;

    return $resultset;
}

However, I do not like the fact that I have to specify the column name of the primary key and supply it to the function. Is there a way I can determine the value of the primary key for each record, something like mysql_insert_id, but for my case something like the last fetched id?

A: 

According to this, you can get the primary key of a table via:

SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
  AND t.table_schema='db'
  AND t.table_name='tbl';

But, honestly, I'd just go with having to know the primary key in order to index by it. The primary key can be a multi-part key, for instance. It's not as simple as you think.

Borealid