Search code examples
phpmysqlstring-parsing

Is getting a specific bit of information from a mysql column possible?


Say I have a mysql table of names and one column has the following name inside it -

| id |         name            |
| 1  | "Robert Downey Junior"  |

and I only want to echo from this column part of the name: "Downey"

I know the most optimal way of doing this would be to have three separate columns for first name, second name and surname, however is it possible to extract just a part of that name if the full name was inside one column?

Note: I would like to point out that I would need the full name in another place and the easiest way to put the names into the database is the full name - as there are literally thousands of names.


Solution

  • Since all the names are formatted the same (First Middle Last, space separated), you can do:

    $result = mysql_query( 'SELECT name FROM table WHERE id = 1');
    $row = mysql_fetch_assoc( $result);
    $name = explode( ' ', $row['name']);
    echo $name[1]; // "Downey"