简体   繁体   中英

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?

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');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM