tags:

views:

52

answers:

2

What I am trying to accomplish here is to separate a firstname, lastname combo to store in a database. I already added the the new columns in the database to hold the first and last names. What I need to do now is to actually separate them and run an SQL update against the changes.

Can someone please give me a hand? Thanks.

Here is my code

<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db("test",$link);

$sql = "SELECT * FROM new_users";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
    $foo[] = $row;
}

foreach($foo as $name)
{
    $_name[] = explode(',',$name['Name']);
    $_pan[] = $name['PANumber'];
}

foreach($_pan as $pan)
{
    foreach($_name as $name)
    {
        echo'<pre>';
        print_r($pan);
        echo'</pre>';
    }
}
+4  A: 

If I'm understanding your question, you've got a Name column which is "first,last" and you want to replace it with First and Last columns.

SQL's string manipulation is probably easiest:

UPDATE new_users SET First=SUBSTRING_INDEX(Name, ",", 1), Last=SUBSTRING_INDEX(Name, ",", -1)

... then, after you're sure it did the right thing:

ALTER TABLE new_users DROP Name

gavinandresen
+1 - I like your answer better than mine - best to do it all in the database if possible.
Eric Petroelje
Yeah, this is much cleaner. I was using explode. I will try this one now. Thanks for the help
I'm a bit confused Gavin.. I need to encapsulate this SQL statement inside of a PHP foreach loop, right?
@Jim - no, just run it directly on the server - no need for PHP at all.
Eric Petroelje
Hi Eric, thanks again for the help. I am getting an error when i run this,. "Warning: Wrong parameter count for mysql_query()" Any ideas? Also... I have 84 rows where I need to seperate these names. How will this work without a loop?
I got it Eric. Thank you! I had a syntax error. I fixed that and it worked. Thanks again.
A: 

Something like this aught to work (I assume PANumber is your primary key here?):

foreach($foo as $name)
{
    $_name[] = explode(',',$name['Name']);
    $_pan = $name['PANumber'];

    $sql = "UPDATE new_users SET " . 
           "FirstName = '" . $_name[0] . "' " .
           "LastName = '" . $_name[1] . "' " .
           "WHERE PANumber = '" . $_pan;

    mysql_query($sql);
}
Eric Petroelje
Hey Eric, thanks for the help. Unfortunately, I only get "Array" for the $_name variable when I echo it which was what I had before. Any ideas?