Reputation: 134
Am using bellow php pdo to insert user blog post into my database but am getting error like this Fatal error: Call to a member function prepare() on a non-object in /public_html/postaction.php on line 34
i have tried to fix but keep giving me different errors. is there any other way to do this or fix this one am using?
<?php
if($_POST) {
$sql = "INSERT INTO blog_post(BID,
blog_title,
blog_body,
comments,
UserName,
Time,
Date,
likes,
ip) VALUES (
:BID,
:blog_title,
:blog_body,
:comments,
:UserName,
:Time,
:Date,
:likes,
:ip)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':BID', $newId, PDO::PARAM_STR);
$stmt->bindParam(':blog_title', $_POST['blog_title'], PDO::PARAM_STR);
$stmt->bindParam(':blog_body', $_POST['blog_body'], PDO::PARAM_STR);
$stmt->bindParam(':comments', $_POST['comments'], PDO::PARAM_STR);
$stmt->bindParam(':UserName', $_POST['UserName'], PDO::PARAM_STR);
$stmt->bindParam(':Time', $_POST['Time'], PDO::PARAM_STR);
$stmt->bindParam(':Date', $_POST['Date'], PDO::PARAM_STR);
$stmt->bindParam(':likes', $_POST['likes'], PDO::PARAM_STR);
$stmt->bindParam(':ip', $_POST['ips'], PDO::PARAM_STR);
$stmt->execute();
$newId = $pdo->lastInsertId();
header('location: postblog.php?d=1');
}
else if(!isset($_POST)){
header('location: postblog.php?err=1');
echo "Sorry!";
}
else{
header('location: postblog.php?else=1');
}
?>
Upvotes: 0
Views: 5641
Reputation: 596
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO table(firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "sample";
$lastname = "lastsamp";
$email = "[email protected]";
$stmt->execute();
header("Location: ."); // a redirect is a must after successful POST request
Upvotes: 4