Selecting MYSQL rows with same field names and adding a prefix

前端 未结 2 1975
星月不相逢
星月不相逢 2021-01-21 05:08

I\'m trying to make a mysql query to select several tables and LEFT join them, however they all have same columns names \'user\' etc. I want to rename all the fields in this man

2条回答
  •  长情又很酷
    2021-01-21 05:56

    I totally understand your problem about duplicated field names.

    I needed that too until I coded my own function to solve it. If you are using PHP you can use it, or code yours in the language you are using for if you have this following facilities.

    The trick here is that mysql_field_table() returns the table name and mysql_field_name() the field for each row in the result if it's got with mysql_num_fields() so you can mix them in a new array.

    You can also modify the function to only add the "column." prefix when the field name is duplicated.

    Regards,

    function mysql_rows_with_columns($query) {
        $result = mysql_query($query);
        if (!$result) return false; // mysql_error() could be used outside
        $fields = mysql_num_fields($result);
        $rows = array();
        while ($row = mysql_fetch_row($result)) { 
            $newRow = array();
            for ($i=0; $i<$fields; $i++) {
                $table = mysql_field_table($result, $i);
                $name = mysql_field_name($result, $i);
                $newRow[$table . "." . $name] = $row[$i];
            }
            $rows[] = $newRow;
        }
        mysql_free_result($result);
        return $rows;
    }
    

提交回复
热议问题