I'd do this:
$fname = isset($_POST['firstname']) && strlen($_POST['firstname']) > 0 ? $_POST['firstname'] : null;
This way, $fname will be defined to the $_POST['firstname'] value if the variable is set and not empty, otherwise it will be null
By the way, if you're working inside double quotes ("
), there's no need to use a dot to add values to the $sql string. Even more, your syntax is wrong. This is a working way to do it:
$sql = "UPDATE profile SET first='$fname', last='$lname' WHERE id='$id'";
You should NOT use this kind of SQL-query generation. It's vulnerable to SQL injections. Better use PDO or MySQLi parametrized queries.
And, by the way, if you want to deny the insertion if a value is empty, you better do it when creating the MySQL table (assigning a not null
property to the column). For example:
CREATE TABLE user(
first VARCHAR(50) NOT NULL,
last VARCHAR(50) NOT NULL
)
** EDIT: If I'm understanding well, this is that you want:
$valuesToAdd = "";
// Concatenate values to the query if they are defined
if (isset($_POST['firstname']) && strlen($_POST['firstname']) > 0) $valuesToAdd .= "first = '{$_POST['firstname']}',";
if (isset($_POST['lastname']) && strlen($_POST['lastname']) > 0) $valuesToAdd .= "last = '{$_POST['lastname']}',";
// Repeat for any other values...
// By default, the SQL string is empty
$sql = "";
// If changes were made...
if (strlen($valuesToAdd) > 0) {
// Remove the last ","
$valuesToAdd = substr($valuesToAdd, 0, strlen($valuesToAdd)-1);
// Generate the SQL string with the values which will be added
$sql = "UPDATE profile SET {$valuesToAdd} WHERE id='{$id}'";
// echo $sql; die;
}
// Check if the SQL string is not empty
if (strlen($sql) > 0) {
// Here the SQL has been generated, use it for a SQL query...
// $con = mysql_connect(...); .....
}