Jump to content

mysql_fetch_field alternative with large table


leo_divinci

Recommended Posts

hi all, thought I would ask some opinions on the below function.

it is for a site of mine that has a table that is always growing it is an X->Y table, each column(x) and each row(y)

 

It is set out like this:

 

table test

    id---col1---col2---col3---col4---col5      <- the tables columns `id` being the key

    0      1        2        3        4        5        <- the first row of the table

    1

    2

    3

    4

    5

 

Now for every column, there is a corresponding row.

There will be in theory unlimited columns/rows! (Not really unlimited but you get the point)

Each column name is an individual name, not just col{x}.

 

function getColumnID($column)
{
if(mysql_fetch_field($column))   <- Returns an error is false
	{
	$MysqlQueryString = 'SELECT `'.$column.'` FROM `test` WHERE `id`=1 LIMIT 1';
	$MysqlRow = mysql_fetch_row($MysqlQueryString);
	return $MysqlRow[$column];
	} else return NULL;
}

 

The quickest way for me to find out if a column exists is to use mysql_fetch_field($column) to get it - the above code works, but returns an error message when the column doesn't exist.  If a column does exist it will carry on fine.  This I think is because mysql_fetch_field doesn't just return NULL but returns an error if the column isnt present.

 

The *PROPER* way for me to do this would be to fetch all column names and loop through them - but this is really quite unnecessary, especially when there could be tens of thousands of columns to go though.

 

So are there any better ways you guys could think of?  Or will I have to just bite the error message.

 

Thanks! Nick

 

 

 

 

use mysql_num_rows($MysqlQueryString) to see if there are any rows returned:

 

function getColumnID($column)
{
    if(mysql_fetch_field($column))   <- Returns an error is false
    {
         $MysqlQueryString = mysql_query('SELECT `'.$column.'` FROM `test` WHERE `id`=1 LIMIT 1');

         if (mysql_num_rows($MysqlQueryString))
         {
              $MysqlRow = mysql_fetch_row($MysqlQueryString);

              return $MysqlRow[$column];
         }
         else return NULL;
    } 
    else return NULL;
}

 

EDIT: I just realized there was no mysq_query call to get a result set!!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.