leo_divinci Posted May 11, 2007 Share Posted May 11, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/50941-mysql_fetch_field-alternative-with-large-table/ Share on other sites More sharing options...
fenway Posted May 11, 2007 Share Posted May 11, 2007 Unlimited columns? Quote Link to comment https://forums.phpfreaks.com/topic/50941-mysql_fetch_field-alternative-with-large-table/#findComment-250648 Share on other sites More sharing options...
bubblegum.anarchy Posted May 11, 2007 Share Posted May 11, 2007 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!! Quote Link to comment https://forums.phpfreaks.com/topic/50941-mysql_fetch_field-alternative-with-large-table/#findComment-250981 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.