5

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.

1 Answer 1

8

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)
);
Sign up to request clarification or add additional context in comments.

2 Comments

This solution doesn't work when $param1 text is long and have new lines etc. It doesnt escape it.
Thank you, this one worked. I think I tried every other combination with raw statement. I even tried to get PDO instance and do it from PDO level but that would be counter productive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.