Check if Field Exists in Mysql Table

Sometimes it is useful to know if a field exists in a mysql table before running a query using that field name, especially when the field name is coming from some kind of user input.

So to do this we use the function mysql_list_fields to grab the fields out of a table and run through them with a for loop until we find the one we are looking for – using the function mysql_field_name, in which case we return true. If we don’t find it, the function returns false.

[code lang=”php”]

[/code]

And it’s that easy!

Filed under: MySQL, PHP, TutorialsTagged with: , , , ,

1 Comment

  1. Just another approach for checking on the availability of a column using PHP:

    $chkcol = mysql_query(“SELECT * FROM `table_name` LIMIT 1”);
    $mycol = mysql_fetch_array($chkcol);
    if(isset($mycol[‘my_column’]))
    echo “Column my_column exists! Do something…”;


Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *
Website