This procedural function will tell you if the table you are looking for is found within your currently selected MySQL database. Optionally, it will also determine if a column exists within the specified table. You can even pass the a value as the optional third parameter to see if the field’s value is also what you expect.
function match_table_field($table, $field = NULL, $value = NULL) {
$table = mysql_escape_string($table);
$query = mysql_query("SHOW TABLES LIKE '{$table}'");
if (mysql_num_rows($query)) {
if (empty($field)) {
return TRUE;
} else {
$sql = "SELECT * FROM `{$table}`";
if ($value) {
$value = mysql_escape_string($value);
$sql .= " WHERE `{$field}` = '{$value}'";
}
$query = mysql_query($sql);
if (mysql_num_rows($query)) {
if (empty($value)) {
$row = mysql_fetch_array($query);
return isset($row[$field]);
} else {
return TRUE;
}
}
}
}
return FALSE;
}
I posted a similar suggestion in the Open Cart forums as a possible method to better automate Open Cart’s upgrade script.
Note: I converted the above example written for Open Cart to procedural PHP to reduce confusion and for the sake of simplicity 😉