phpmysqlsql-updateaddslashes

Escaping MySQL UPDATE (IF LENGTH)


I've created an UPDATE statement that updates only if the string's length is greater than 0.

I'm trying to escape quotes within my UPDATE statement once the condition is met. I've been using addslashes($name), but with this new condition addslashes no longer works.

Previous:

$mysqli->query("UPDATE table SET name='".addslashes($name)."' WHERE id=1") or die($mysqli->error);

Current:

$mysqli->query("UPDATE table SET name=IF(LENGTH($name)=0, name, '$name') WHERE id=1") or die($mysqli->error);

Where do I place addslashes() for this function to correctly escape characters? Will this function even work within this particular MySQL statement for PHP?


Solution

  • The problem with your second query is that $name inside the call to LENGTH needs to be in quotes too i.e.

    $mysqli->query("UPDATE table SET name=IF(LENGTH('$name')=0, name, '$name') WHERE id=1") or die($mysqli->error);
    

    To use addslashes in that query, you would write:

    $mysqli->query("UPDATE table SET name=IF(LENGTH('".addslashes($name)."')=0, name, '".addslashes($name)."') WHERE id=1") or die($mysqli->error);
    

    But really you should consider using a prepared statement instead; then you won't have to worry about escaping quotes. Additionally, you should check the length of $name in PHP and not run the query at all if it is empty. Something like this should work (I'm assuming you have a variable called $id which stores the id value for the update).

    if (strlen($name)) {
        $stmt = $mysqli->prepare("UPDATE table SET name=? WHERE id=?");
        $stmt->bind_param('si', $name, $id);
        $stmt->execute() or die($stmt->error);
    }
    

    If you have multiple pieces of data to update, you could try something like this:

    $name = 'fred';
    $city = '';
    $state = 'SA';
    $id = 4;
    $params = array();
    foreach (array('name','city','state') as $param) {
        if (strlen($$param)) $params[$param] = $$param;
    }
    $sql = "UPDATE table SET " . implode(' = ?, ', array_keys($params)) . " = ? WHERE id = ?";
    $types = str_repeat('s', count($params)) . 'i';
    $params['id'] = $id;
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute() or die($stmt->error);