The method for PHP to query whether a field in mysql exists is: 1. Use SQL statements to query the information architecture, execute a "SHOW COLUMNS FROM" command to obtain information about all columns in the specified table, and then traverse the results in the result set The column name checks whether the specified field appears; 2. Use the SELECT query statement to verify and try to access the field to check whether it exists, but it is not suitable for situations where access rights are insufficient.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
In php, you can use the following two methods to determine whether a certain field exists in the MySQL database table.
Method 1: Use SQL statements to query the information architecture
You can obtain the information of all columns in the specified table by executing a "SHOW COLUMNS FROM" command, and then traverse the results Centralized column names check whether the specified field appears. For example:
function checkColumnExist($column_name, $table_name, $mysqli_link) { $query = "SHOW COLUMNS FROM ".$table_name; $result = mysqli_query($mysqli_link, $query); if ($result !== false) { while ($row = mysqli_fetch_assoc($result)) { if (strtolower($row['Field']) === strtolower($column_name)) { return true; } } } return false; }
This function will return a Boolean value indicating whether the specified column name exists in the specified table.
Method 2: Use SELECT query statement to verify
You can also initiate a SELECT query request and try to access the field to check whether it exists. Note that this approach may require more resources and may not work in all situations (e.g. where access rights are insufficient). For example:
function checkColumnExist($column_name, $table_name, $mysqli_link) { $query = "SELECT `$column_name` FROM `$table_name` LIMIT 1"; $result = mysqli_query($mysqli_link, $query); return $result !== false; }
This function will also return a Boolean value indicating whether the specified column name exists in the specified table.
The above is the detailed content of How to query whether a field in mysql exists in php. For more information, please follow other related articles on the PHP Chinese website!