如何为字符串设置默认值?

I have a page that imports fields from a csv file and imports them into my database. Before the fields can be imported into my database I need to separate the name field into two separate values (first name & last name). I do it like so:

$name = $order[5];
$fname = sqlSafe(trim(substr($name, 0, strrpos($name, " "))));`
$lname = sqlSafe(trim(substr($name, strrpos($name, " "))));`

This seems to work reasonably well, but sometimes the name field has been left partially complete (they've entered just their first name or last name for example). This results $fname being blank and mysql won't allow me to set a default value for a BLOB/TEXT column.

To solve this I have tried a couple of if statements including:

if (!$fname) {$fname = "(blank)";}
if ($fname = "") {$fname = "(blank)";}
if ($fname = NULL) {$fname = "(blank)";}

None of which seem to catch it. Where am I going wrong?

The single = in your ifs will actually not test but assign a value. Use ==or better === to test with if.

More info on test operators: http://www.php.net/manual/en/language.operators.comparison.php

explode $name with space, and see the number of result.

$result = explode($name, ' ');
if (count($result) == 1) {
    $fname = $result[0];
    $lname = '';
} else {
    $fname = $result[0];
    $lname = $result[1];
}

You can also do the check immediately in the assignment:

$name = $order[5];
$fname = sqlSafe(trim(substr($name, 0, strrpos($name, " ")))) ?: '(blank)';
$lname = sqlSafe(trim(substr($name, strrpos($name, " ")))) ?: '(blank)';

Note the ?:, that's the ternary operator syntax.

Use == instead of = to compare your string

Notice that strrpos as well as substr might return FALSE instead of an int/string. You should check that first before decomposing $name. http://www.php.net/manual/en/function.substr.php ...

Having said that, explode is the function you are looking for. ;) http://www.php.net/explode