Forum Moderators: coopster
1. Check to see if the table already has the fields in question.
2. If it has the fields, run a query.
3. If it doesn't have the fields, add the fields and then run the query.
These are the areas I am getting stuck on:
How do I check a table to see if it has the field I am looking for? By running a check to see if those fields exist before running the query am I going to be producing a lot of overhead?
I needed this one time, might give you some insight as well
getting information about mysql tables and fields with php [webmasterworld.com] msg16
// This function will check to see if a field exists in a table
function fieldExists($table, $field)
{
$ret = FALSE;
$q = "DESC ".$table;
$fields = getSelectArray($q);
foreach($fields as $val)
{
if($val['Field'] == $field)
$ret = TRUE;
}
return $ret;
} // end function fieldExists()
So if the field does not exist I run the query to alter the table and add it:
if(!fieldExists('mytable', 'myfield')
{
$q = "ALTER TABLE `mytable` ADD `myfield` VARCHAR(16) NOT NULL AFTER `anotherfield`";
mysql_query($q);
} Just in case anyone is wondering what getSelectArray() does, here it is:
// This function creates an associative, multidimensional array from a SQL SELECT statement.
function getSelectArray( $query )
{
$res = mysql_query( $query );
$resnum = mysql_num_rows( $res );
for ( $i = 0; $i < $resnum; $i++ )
{
$t[$i] = mysql_fetch_assoc( $res );
}
return $t;
} // end function getSelectArray( )
I use this for getting results for all SELECT queries; using a foreach loop it is easy to throw results into a table.