Jump to content

Trying to convert column from full name field to first and last name fields


Go to solution Solved by Barand,

Recommended Posts

I'm trying to do this with the code below.  I get an error because explode thinks I'm just sending it one argument since the string is held by an array element.  If I can get the array from the explode function I can insure it into the first and last name fields in my table.

Any suggestions?

--Kenoli

require '__classes/Db.php';

$sql = "SELECT name FROM tbl_persons";
$stmt = $pdo->query($sql);
$row = $stmt->fetchall(PDO::FETCH_ASSOC);

foreach ($row as $name) {
	 $names = explode($name['name']);
	}

 

Link to post
Share on other sites

Alternaltive method...

mysql> SELECT * FROM users;
+--------+--------------+-----------+----------+
| userId | fullname     | firstname | lastname |
+--------+--------------+-----------+----------+
|      1 | Peter Dowt   | NULL      | NULL     |
|      2 | Laura Norder | NULL      | NULL     |
|      3 | Tom DiCanari | NULL      | NULL     |
|      4 | Scott Chegg  | NULL      | NULL     |
+--------+--------------+-----------+----------+


mysql> UPDATE users
    -> SET firstname = SUBSTRING_INDEX(fullname, ' ', 1),
    ->     lastname  = SUBSTRING_INDEX(fullname, ' ', -1);


mysql> SELECT * FROM users;
+--------+--------------+-----------+----------+
| userId | fullname     | firstname | lastname |
+--------+--------------+-----------+----------+
|      1 | Peter Dowt   | Peter     | Dowt     |
|      2 | Laura Norder | Laura     | Norder   |
|      3 | Tom DiCanari | Tom       | DiCanari |
|      4 | Scott Chegg  | Scott     | Chegg    |
+--------+--------------+-----------+----------+

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.