Home > Article > Backend Development > How to query whether a specified field in mysql exists in php
In PHP, if we want to query whether a field in the MySQL table exists, we can use the following two methods:
<?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 and
$dbname in the above code are respectively Represents the database server name, username, password, and database name.
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.
<?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,
$username## in the above code #, $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. Generally speaking, the former is more concise than the latter, but the query results of the latter are more detailed, and you can obtain the field type, length, default value and other information. Just choose to use it according to the actual situation.
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!