I have a table which contains rows, within each row there is a field which contains peoples names seperated by a double space.
I need to extract this field from each row, then split the field into separate names and dump into another table.
What's the best way to do this? Do I split it within the sql query or extract the fields then split using PHP?
New info:
OK, the field contains full names e.g. john doe, tom smith etc etc the double spaces separate the full names e.g.
JOHN DOE TOM SMITH JOHN WOO
There might be one name in the field but there could also be potentialy up to 10
Thanks
Darren
you can do it in sql. should be something like this:
INSERT INTO tbl_dest (first_name, last_name) VALUES
(SELECT
LEFT(ts.name, LOCATE(' ',ts.name)) AS first_name,
SUBSTRING(ts.name, LOCATE(' ',ts.name)+2) AS last_name
FROM tbl_source AS ts)
as @Marc B stated, it will only work if the data is consistent (ie each row's name field contains a double space and the first double space separates the name and password. you can ignore other rows (without the double space) by simply adding
INSERT ...
(SELECT ...
FROM tbl_source AS ts WHERE LOCATE(' ', ts.name) > 0)
if the field starts with a double space (ie first name is empty) it will also be ignored
EDIT:
since you said that each row can contain multiple pairs of first/last name. here's a code example:
$query = "SELECT `name` FROM `tbl_source`";
$res = mysql_query($query, $link);
$names = array();
while ($row = mysql_fetch_assoc($res)) {
$nmlist = explode(' ',$row['name']);
for($i=0, $n=count($nmlist); $i<$n-1; $i+=2){
$names[] = "('" . mysql_real_escape_string(stripslashes($nmlist[$i])) ."',"
."'" . mysql_real_escape_string(stripslashes($nmlist[$i+1])) ."')";
}
}
$insert_query = "INSERT INTO `tbl_dest` (`first_name`,`last_name`) VALUES "
.implode(',', $names);
mysql_query($insert_query, $link);
in this example, double spaces are between first name and last name, and between each pair
I'm not familiar with a MySQL solution for this.
I suggest grabbing the information you need, using explode(' ', $info);
and then inserting back into the database.