Using WordPress ‘check_column()’ PHP function

The check_column() WordPress PHP function checks whether a database table column matches the given criteria. It uses the SQL DESC command to retrieve the table info for the column. This function is useful when you want to check specific characteristics of a database column, such as its type, default value, and more.

Usage

Here’s a general example of how you can use this function:

$result = check_column('users', 'email', 'varchar', true, 'PRI', 'none', 'auto_increment');

In this case, the function will check whether there’s a column named ’email’ in the ‘users’ table, if its type is ‘varchar’, if it’s nullable, if it’s a primary key, if its default value is ‘none’, and if its extra value is ‘auto_increment’. It will return a boolean value indicating if the column matches all these criteria.

Parameters

  • $table_name (string) – The name of the database table you want to check.
  • $col_name (string) – The name of the table column you want to check.
  • $col_type (string) – The type of the table column you want to check.
  • $is_null (bool, optional) – Whether to check if the column is nullable. Pass in null to skip this check.
  • $key (mixed, optional) – The key info of the column. Pass in null to skip this check.
  • $default_value (mixed, optional) – The default value of the column. Pass in null to skip this check.
  • $extra (mixed, optional) – The extra value of the column. Pass in null to skip this check.

More information

See WordPress Developer Resources: check_column()

This function is not deprecated and is currently in use. For source code and more detailed information, refer to the official WordPress Developer Resources page.

Examples

Check if a ‘username’ column of type ‘varchar’ exists in ‘users’ table

$result = check_column('users', 'username', 'varchar', null, null, null, null);

This checks whether there’s a ‘username’ column of type ‘varchar’ in the ‘users’ table. It ignores other checks by passing null to them.

Check if a ‘created_at’ column of type ‘datetime’ and default value ‘CURRENT_TIMESTAMP’ exists in ‘users’ table

$result = check_column('users', 'created_at', 'datetime', null, null, 'CURRENT_TIMESTAMP', null);

This checks whether there’s a ‘created_at’ column of type ‘datetime’ with default value ‘CURRENT_TIMESTAMP’ in the ‘users’ table.

Check if a nullable ’email’ column exists in ‘users’ table

$result = check_column('users', 'email', 'varchar', true, null, null, null);

This checks whether there’s a nullable ’email’ column in the ‘users’ table.

Check if a ‘id’ column of type ‘int’ and as a primary key exists in ‘users’ table

$result = check_column('users', 'id', 'int', null, 'PRI', null, null);

This checks whether there’s an ‘id’ column of type ‘int’ and it is a primary key in the ‘users’ table.