简体   繁体   中英

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

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

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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