[英]why is this PDO insert not working?
please help , this is not inserting into db 请帮助,这不是插入数据库
$dbh = new PDO('mysql:host=localhost;dbname=blog', root, root);
if($dbh){
// use the connection here
$stmt = $dbh->prepare("INSERT INTO comments (blog_id,dateposted,name,comment) VALUES (:blog_id,:dateposted,:name,:comment)");
$stmt->bindParam(':blog_id', $validentry);
$stmt->bindParam(':dateposted', NOW());
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->execute();
// and now we're done; close it
}else{
echo mysql_error();
}
$dbh = null;
//redirect after posting
$stmt->bindParam(':dateposted', NOW()); $ stmt-> bindParam(':dateposted',NOW());
PDOStatement::bindParam()
binds the parameter to a PHP variable reference. PDOStatement::bindParam()
将参数绑定到PHP变量引用。 As such, it requires the second argument to be a variable. 因此,它要求第二个参数是一个变量。
You can instead use PDOStatement::bindValue()
to use a literal or return value from a function. 您可以改用PDOStatement::bindValue()
来使用文字或从函数返回值。
Also, NOW()
is not a PHP function and as such, cannot be used here. 另外, NOW()
不是PHP函数,因此不能在此处使用。 If you're just wanting to use the DB function, hard-code it into the statement, eg 如果您只想使用DB函数,请将其硬编码到语句中,例如
INSERT INTO comments (blog_id,dateposted,name,comment)
VALUES (:blog_id, NOW(), :name, :comment)
Phil, ok, but if you need the bindParam to assign a value depending a condition? Phil,好的,但是如果您需要bindParam根据条件分配值?
In my case, I want to let the user define the creation date if he wants to. 就我而言,我想让用户定义创建日期。
$stmt = $conn->prepare('INSERT INTO news (title_fr, content_fr, creation_date) VALUES (:title_fr, :content_fr, :creation_date)');
if( $date ) {
$stmt->bindParam(':creation_date', $date);
} else {
$stmt->bindParam(':creation_date', NOW());
}
将NOW()
更改为date('Ymd H:i:s')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.