繁体   English   中英

为什么此PDO插件不起作用?

[英]why is this PDO insert not working?

请帮助,这不是插入数据库

$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());

PDOStatement::bindParam()将参数绑定到PHP变量引用。 因此,它要求第二个参数是一个变量。

您可以改用PDOStatement::bindValue()来使用文字或从函数返回值。

另外, NOW()不是PHP函数,因此不能在此处使用。 如果您只想使用DB函数,请将其硬编码到语句中,例如

INSERT INTO comments (blog_id,dateposted,name,comment)
VALUES (:blog_id, NOW(), :name, :comment)

Phil,好的,但是如果您需要bindParam根据条件分配值?

就我而言,我想让用户定义创建日期。

    $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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM