【问题标题】:Trying to build my query by fetching column names from the selected table尝试通过从选定表中获取列名来构建我的查询
【发布时间】:2018-12-10 16:43:53
【问题描述】:

我正在自动和动态地生成 SQL 查询,以便将 CSV 数据插入到选定的数据库中。现在我有一个包含 10 个不同数据库的列表。现在我很好奇是否可以通过从数据库中获取列名来动态构建我的查询的一部分(表名)?

这是我现在拥有的代码,但它不太有效:

function getTableDetails($table_name) {
    global $con, $user;

    $describeTable = mysqli_query($con, "DESCRIBE " . $user . "." . $table_name);

    $fields = [];
    while($show = mysqli_fetch_fields($describeTable)) {
        $fields['column_name'][] = $show['COLUMN_NAME'];
        $fields['column_length'][] = $show['CHARACTER_MAXIMUM_LENGTH'];
        $fields['column_type'][] = $show['COLUMN_TYPE'];
    }

    return $fields;
}

我如何尝试获取它们

$table = getTableDetails($settings_type);
foreach ($table['column_name'] as $columnName) {
    print_r($columnName);
}

【问题讨论】:

  • 变量 $user 在这种情况下是数据库名称
  • 另见information_schema.columns

标签: php mysql innodb procedural-programming


【解决方案1】:

我稍微更改了函数以传递您使用global 访问的字段(因为不推荐这样做)。因此,您必须将呼叫更改为 getTableDetails()

mysqli_fetch_fields() 用于返回作为结果集一部分的字段,因为这是来自describe,您获取的是描述返回值的字段,而不是表中的字段。相反,您需要使用 mysqli_fetch_assoc() 从语句中返回数据行。

要始终检查的另一件事是,如果您在获取数据时遇到问题,请使用 print_r() 检查返回的内容。

我还按列名对数据进行了索引,这有时很有用,但您也可以只使用$fields[] = [...

由于字段长度不是要返回的字段集的一部分,所以我添加了将从数据类型中提取它的代码,因此 int(11) 具有使用 @987654332 从括号之间提取的值 11 @。

function getTableDetails( $con, $user, $table_name) {
    $describeTable = mysqli_query($con, "DESCRIBE " . $user . "." . $table_name);

    $fields = [];
    while($show = mysqli_fetch_assoc($describeTable)) {
        $columnName = $show['Field'];
        // Extract length from field type (if any)
        preg_match('#\((.*?)\)#', $show['Type'], $match);
        $fields[$columnName] = ['column_name' => $show['Field'],
            'column_length' => $match[1]??0,
            'column_type' => $show['Type']];        
    }

    return $fields;
}

$table = getTableDetails( $con, $user, "articles");
foreach ($table as $columnName) {
    print_r($columnName);
}

【讨论】:

  • 感谢您的快速帮助!还有一种方法可以跳过数组中的前 3 个项目,因为 CSV 文档不包含这些项目(id、uid、tid)并且它们可能不会在插入查询中使用,因为它们是从服务器端提供的
  • 如果只需要删除数组开头的项目array_shift().
  • 感谢您的帮助,它解决了我的问题 :D 您能否解释一下为什么我应该避免使用“global”?
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多