Babita Bhandari Babita Bhandari - 4 months ago 11
MySQL Question

Show column names from table as pascal case

I have created a table in phpmyadmin with column names like

first_name
,
last_name
. When I use the command to show column names from the table, it displays them as
first_name
.

I want to display my column names like
First Name
. Can you please tell me how to show column names in pascal case.

Answer

This code converts some_text to Some Text:

$before = array('first_name', 'last_name', 'something');

$after = array();
foreach($before as $v){
    $after[] = ucwords(implode(' ', explode('_', $v)));
}

Result:

Array
(
    [0] => First Name
    [1] => Last Name
    [2] => Something
)

And another way of doing the same:

// .. foreach ..
$after[] = implode(' ', array_map('ucfirst', explode('_', $v)));
// code

The output is the same as before.



The following example shows how to do it when running SHOW COLUMNS FROM TABLENAME. I used PDO. Take a look:

$con = new PDO('con string here', 'DB_USERNAME', 'DB_PASSWORD');
$stmt = $con->prepare('SHOW COLUMNS FROM tablename');
$stmt->execute();
$columns = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $columns[] = array(
        'original' => $row['Field'],
        'pascal' => ucwords(implode(' ', explode('_', $row['Field'])))
    );
}

The result of $columns will be something like this:

Array
(
    [0] => Array
        (
            [original] => first_name
            [pascal] => First Name
        )

    [1] => Array
        (
            [original] => last_name
            [pascal] => Last Name
        )

    [2] => Array
        (
            [original] => other_column
            [pascal] => Other Column
        )

    [3] => Array
        (
            [original] => something
            [pascal] => Something
        )

)
Comments