Question

I'm trying to create mysql UPDATE query that will take parameters. In addition I want to append to the end of the field if the field isnt empty. For that I'm using CASE statement. Here's my query in doctrine (from silex):

$query = "UPDATE table SET filed = (
CASE WHEN field = ''
THEN :param1
ELSE concat(field, :param1)
END)
WHERE id=:param2";
$app['db']['test_db']->executeUpdate($sql, array('param1' => $user_text, 'param2' => $selected_id));

Now I want to convert it to fluent or raw query so I can use it in Laravel 4.

Here's my code:

$param1 = "String..."; // user string
$param2 = 45; // id
DB:connection('test_db')->statement("UPDATE table SET field =(
case
    WHEN field=''
    THEN $param1 
    ELSE concat(field, $param1)
END)
WHERE id=$param2");

When I execute this query in Laravel I see

Syntax error or access violation: 1064

Any help will be appreciated.

Was it helpful?

Solution

Try running it using raw():

DB::statement(
    DB::raw(
                "UPDATE table SET field =
                    (
                        CASE
                            WHEN field=''
                            THEN ?
                            ELSE concat(field, ?)
                        END
                    )
                    WHERE id=?"
    ),

    array($param1, $param1, $param2)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top