简体   繁体   English

如何根据其他列值输出SQL列?

[英]How can I output SQL columns depending on other column values?

I have a WordPress database I am working on which stores form data from the Front-end. 我有一个WordPress数据库,正在使用该数据库存储前端的表单数据。 When submitting these forms, a parent_id is assigned which matches up to the Wordpress post that they sit on. 提交这些表单时,将分配一个parent_id,该ID与其在其上的Wordpress帖子匹配。

I am going to export the columns and rows into a CSV depending on the WP ID. 我将根据WP ID将列和行导出为CSV。

The main issue I am facing is only exporting the columns that have values. 我面临的主要问题是仅导出具有值的列。

WP数据库表图像

For example, if I exported the CSV on the WP Post of 206 I would need to get all of the columns apart from "Do you want free paper?" 例如,如果我在206的WP帖子上导出了CSV,则需要除“是否要免费用纸?”之外的所有列。 and "Male or Female". 和“男性或女性”。

    global $post;
    global $wpdb;
    $form_id = $post->ID;
    $title = str_replace(' ', '-', get_the_title($form_id));
    $title = preg_replace('/[^A-Za-z0-9\-]/', '', $title);
    $filename = $title . '.csv';
    $table_answers = $wpdb->prefix . "opforms_sub";
    $output = fopen('php://output', 'w');
    $headers = $wpdb->get_col("DESC wp_opforms_sub", 0);

    fputcsv( $output, $headers);

    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename=". $filename);

Many thanks in advance! 提前谢谢了!

You could use following query 您可以使用以下查询

SELECT column_name FROM information_schema.columns WHERE table_name='wp_opforms_sub' LIMIT 0,7

instead of 代替

DESC wp_opforms_sub

Should be 应该

$headers = $wpdb->get_col("SELECT column_name FROM information_schema.columns WHERE table_name='wp_opforms_sub' LIMIT 0,7", 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM