使用php pdo在数据库中插入记录

时间:2016-01-12 16:19:18

标签: php mysql pdo

使用bellow php pdo将用户博客文章插入我的数据库但是我收到了这样的错误Fatal error: Call to a member function prepare() on a non-object in /public_html/postaction.php on line 34我试图修复但是一直给我不同的错误。有没有其他方法可以做到这一点或修复这个使用?

<?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'); 
}
?>

1 个答案:

答案 0 :(得分:2)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $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 = "sample@example.com";
    $stmt->execute();

    echo "New records created successfully";

        //handle the rest action here

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
$conn = null;
?> 

将它与prepare语句一起使用试试这个例子

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?> 

最后试试这个:

<?php 
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASSWORD', "123");
define('DB_DATABASE', "test");
define('DB_DRIVER', "mysql");

$country = 'Canada';
$capital = 'Ottawa';
$language = 'English & French';

try {
    $db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("INSERT INTO countries(name, capital, language) VALUES (:country, :capital, :language)");

    $stmt->bindParam(':country', $country, PDO::PARAM_STR, 100);
    $stmt->bindParam(':capital', $capital, PDO::PARAM_STR, 100);
    $stmt->bindParam(':language', $language, PDO::PARAM_STR, 100);

    if($stmt->execute()) {
      echo '1 row has been inserted';  
    }

    $db = null;
} catch(PDOException $e) {
    trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}

?>

OR

$sql = "INSERT INTO movies(filmName,
            filmDescription,
            filmImage,
            filmPrice,
            filmReview) VALUES (
            :filmName, 
            :filmDescription, 
            :filmImage, 
            :filmPrice, 
            :filmReview)";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':filmName', $_POST['filmName'], PDO::PARAM_STR);       
$stmt->bindParam(':filmDescription', $_POST['filmDescription'], PDO::PARAM_STR); 
$stmt->bindParam(':filmImage', $_POST['filmImage'], PDO::PARAM_STR);
// use PARAM_STR although a number  
$stmt->bindParam(':filmPrice', $_POST['filmPrice'], PDO::PARAM_STR); 
$stmt->bindParam(':filmReview', $_POST['filmReview'], PDO::PARAM_STR);   

$stmt->execute();