Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify 'default' in a parameterized PHP PDO insert?

Tags:

php

mysql

pdo

I came up with a workaround for now, but I'm curious for future reference...

If a mysql table column is defined as NOT NULL but has a default value, that default value will be inserted if the column name is not specified in the insert statement, OR if you specify the keyword DEFAULT as the value. If you specifically use NULL as a value on a NOT NULL column, even if the column has a default, it will try to insert the NULL and throw an error.

But is there any way to specify the DEFAULT keyword as a value in a parameterized INSERT statement? I don't want to just omit the column from the insert statement, because I want to use the same statement with multiple data sets, some of which actually have data for that column.

like image 370
ChrisNY Avatar asked May 26 '14 19:05

ChrisNY


People also ask

What is PDO :: Param_str?

PDO::PARAM_STR. Represents SQL character data types. For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to the type of data being bound. Set the fourth parameter, length , to the maximum expected length of the output value.

Does PDO use prepared statements?

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

What is PDO parameter binding?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name. This function bound the variables, pass their value as input, and receives the output value, if any, of their associated parameter marker.

What does the Prepare method of a PDO object return when called successfully?

Return Values ¶ If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns false or emits PDOException (depending on error handling).


1 Answers

If you want an INSERT statement that treats NULL as the default value for the column, here's a solution:

I created a table:

CREATE TABLE `foo` (
  `x` INT DEFAULT '768'
)

Then I tested a couple of prepared-statement INSERTs with PDO:

$stmt = $pdo->prepare("INSERT INTO foo (x) VALUES (COALESCE(?, DEFAULT(x)))");

$stmt->execute( [ 42 ] ); // inserts a real value

$stmt->execute( [ NULL ] ); // inserts the column's default value 

I confirmed the test:

mysql> select * from foo;
+------+
| x    |
+------+
|   42 |
|  768 |
+------+

Tested with PHP 5.5.12 and MySQL 5.6.17.

like image 155
Bill Karwin Avatar answered Oct 23 '22 02:10

Bill Karwin