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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With