Karina
Karina

Reputation: 661

Set a default value for INSERT statement PHP

I know this should be a simple question, i have the following insert statement which is inserting values captured via a form, all works well but i would also like to add a default value to a column not on my form(lets say language for example), i don't want to add the default value via the database, as i have two forms that are coming together to the one table.

$stmt = DB::query(Database::INSERT,
    'INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`)
    VALUES (:first_name, :initial, :last_name, :street)');                                                      

$stmt->param(':first_name', $post['first_name']);
$stmt->param(':initial', $post['initial']);
$stmt->param(':last_name', $post['last_name']);
$stmt->param(':street', $post['street']);

Is there a way to specify a default value via the above?

Upvotes: 1

Views: 530

Answers (2)

Victor Bocharsky
Victor Bocharsky

Reputation: 12306

You could use my tiny library ValueResolver in this case, for example:

$stmt->param(':my_column', ValueResolver::resolve($post['first_name'], 'default')); // returns 'default' if $post['first_name'] is empty

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

Upvotes: 0

deceze
deceze

Reputation: 522081

What's wrong with this?

$stmt = DB::query(Database::INSERT,
    "INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`, `myColumn`)
    VALUES (:first_name, :initial, :last_name, :street, 'my default value')");

Or possibly:

$stmt = DB::query(Database::INSERT,
    'INSERT INTO `my_products` (`first_name`, `initial`, `last_name`, `street`, `myColumn`)
    VALUES (:first_name, :initial, :last_name, :street, :my_column)');

...
$stmt->param(':my_column', 'my default value');

Upvotes: 3

Related Questions