为什么这个 PDO 插入不起作用?
请帮助,这不是插入到数据库中
$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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PDOStatement::bindParam()
绑定PHP 变量引用的参数。因此,它要求第二个参数是一个变量。您可以使用
PDOStatement::bindValue()
使用函数的文字或返回值。此外,
NOW()
不是 PHP 函数,因此不能在此处使用。如果您只想使用 DB 函数,请将其硬编码到语句中,例如PDOStatement::bindParam()
binds the parameter to a PHP variable reference. 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.Also,
NOW()
is not a PHP function and as such, cannot be used here. If you're just wanting to use the DB function, hard-code it into the statement, eg将
NOW()
更改为date('Ymd H:i:s')
change
NOW()
todate('Y-m-d H:i:s')
Phil,好的,但是如果您需要 bindParam 根据条件分配一个值?
就我而言,如果用户愿意,我想让用户定义创建日期。
Phil, ok, but if you need the bindParam to assign a value depending a condition?
In my case, I want to let the user define the creation date if he wants to.