php – 使用DEFAULT值準備MySQL INSERT / UPDATE語句
引用SQL/">MySQL INSERT手冊 – 同樣適用於UPDATE:
Use the keyword DEFAULT to set a column explicitly to its default value. This makes it easier to write INSERT statements that assign values to all but a few columns, because it enables you to avoid writing an incomplete VALUES list that does not include a value for each column in the table. Otherwise, you would have to write out the list of column names corresponding to each value in the VALUES list.
所以簡而言之,如果我寫
INSERT INTO table1 (column1,column2) values ('value1',DEFAULT);
一個新的行,column2被設定為其預設值 – 無論它是什麼 – 被插入.
但是,如果我在PHP中準備和執行語句:
$statement = $pdoObject-> prepare("INSERT INTO table1 (column1,column2) values (?,?)"); $statement->execute(array('value1','DEFAULT'));
新行將包含“DEFAULT”作為其文字值 – 如果列能夠儲存文字值.
現在我已經寫了一個PDO的抽象層(我需要它),並解決這個問題我正在考慮介紹一個
const DEFAULT_VALUE = "randomstring";
所以我可以執行這樣的語句:
$statement->execute(array('value1',mysql::DEFAULT_VALUE));
然後在做繫結的方法中,我將通過傳送繫結的值,如果有些等於self :: DEFAULT_VALUE,則相應地執行.
我很確定有一個更好的方式來做到這一點.有人遇到類似情況嗎?
例如.
$pdo = new PDO("mysql:host=localhost;dbname=test", 'localonly', 'localonly'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec(" CREATE TEMPORARY TABLE foo ( id int auto_increment, x int NOT NULL DEFAULT 99, y DATETIME NOT NULL DEFAULT '2010-03-17 01:00:00', z varchar(64) NOT NULL DEFAULT 'abc', primary key(id) ) "); $stmt = $pdo->prepare(' INSERT INTO foo (x,y,z) VALUES ( Coalesce(:x, Default(x)), Coalesce(:y, Default(y)), Coalesce(:z, Default(z)) ) '); $stmt->bindParam(':x', $x); $stmt->bindParam(':y', $y); $stmt->bindParam(':z', $z); $testdata = array( array(null, null, null), array(1, null, 'lalala'), array(null, '2009-12-24 18:00:00', null) ); foreach($testdata as $row) { list($x,$y,$z) = $row; $stmt->execute(); } unset($stmt); foreach( $pdo->query('SELECT id,x,y,z FROM foo', PDO::FETCH_NUM) as $row) { echo join(', ', $row), "\n"; }
版畫
1, 99, 2010-03-17 01:00:00, abc 2, 1, 2010-03-17 01:00:00, lalala 3, 99, 2009-12-24 18:00:00, abc
http://stackoverflow.com/questions/2464535/preparing-a-mysql-insert-update-statement-with-default-values