In PHP, if we want to query whether a certain field exists in the MySQL table, we can use the following two methods:
Use DESC command query table structure information
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败:" . $conn->connect_error); } // 查询表结构信息 $sql = "DESC `myTable` `myColumn`;"; $result = $conn->query($sql); // 检查结果是否存在 if ($result->num_rows > 0) { // 如果存在,则执行相应的操作 echo "字段已存在"; } else { // 如果不存在,则执行相应的操作 echo "字段不存在"; } // 关闭连接 $conn->close(); ?>
$servername
, $username
, $password# in the above code ## and
$dbname represent the database server name, user name, password and database name respectively.
myTable and
myColumn represent the name of the database table and the name of the field to be queried respectively. Before executing the above code, please ensure that the corresponding database and tables have been created.
Use INFORMATION_SCHEMA to query field information
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败:" . $conn->connect_error); } // 查询字段信息 $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='" . $dbname . "' AND TABLE_NAME='myTable' AND COLUMN_NAME='myColumn';"; $result = $conn->query($sql); // 检查结果是否存在 if ($result->num_rows > 0) { // 如果存在,则执行相应的操作 echo "字段已存在"; } else { // 如果不存在,则执行相应的操作 echo "字段不存在"; } // 关闭连接 $conn->close(); ?>
$servername,# in the above code ##$username
, $password
, and $dbname
represent the database server name, user name, password, and database name respectively. myTable
and myColumn
represent the name of the database table and the name of the field to be queried respectively. Before executing the above code, please ensure that the corresponding database and tables have been created.
The above is the detailed content of How to query whether a specified field in mysql exists in php. For more information, please follow other related articles on the PHP Chinese website!