0

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?

DJ_Beardsquirt
  • 289
  • 5
  • 14
  • Can you put the next part of the code where you save your data into the DB ? Maybe you're forgetting the quotes in the SQL statements. – Holt Apr 30 '14 at 09:41
  • `sqlSafe` is sounds a bit suspect, remember to [follow this](http://stackoverflow.com/a/60496/2864740). – user2864740 Apr 30 '14 at 09:43

5 Answers5

2

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

Martin Müller
  • 2,565
  • 21
  • 32
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.

giorgio
  • 10,111
  • 2
  • 28
  • 41
1

Use == instead of = to compare your string

Jérôme
  • 292
  • 1
  • 6
0

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];
}
Xing Fei
  • 287
  • 1
  • 6
0

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

Echsecutor
  • 775
  • 8
  • 11