ktm
ktm

Reputation: 6085

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

Upvotes: 0

Views: 766

Answers (3)

Chuck
Chuck

Reputation: 474

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

Upvotes: 0

Phil
Phil

Reputation: 165059

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

Upvotes: 3

Bruce Aldridge
Bruce Aldridge

Reputation: 2937

change NOW() to date('Y-m-d H:i:s')

Upvotes: 0

Related Questions