转换MySql插入到PDO


Converting MySql Insert To PDO

我正在尝试将此转换为PDO:

echo 'sup 1';                                        
$sql = "INSERT INTO blogData(
        title,
        content,
        category) 
        VALUES ( 
        :title, 
        :content, 
        :category)";
     echo 'sup 2';                                 
$stmt = prepare($sql);
                    echo 'sup 3';                          
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);       
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR); 
$stmt->bindParam(':category', 'City Secrets', PDO::PARAM_STR);
                               echo 'sup 4';       
$stmt->execute(); 
echo 'sup 5';
      header('location: http://www.backToThePageIPostedOn.com');

这是我当前的代码,但它没有进入数据库:

$sql = "INSERT INTO blogData(
            title,
            content,
            category) 
            VALUES ( 
            :title, 
            :content, 
            :category)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);       
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR); 
$stmt->bindParam(':category', 'City Secrets', PDO::PARAM_STR);
$stmt->execute(); 
 header('location: http://www.backToThePageIPostedOn.com');

它停在脚本页。这是我第一次使用PDO,所以如果有人能指出我的语法错误,我会很感激。

我的代码没有通过echo 'sup 2';所以我认为错误在这一行,$stmt = $pdo->prepare($sql);

我遵循了一个教程来做这个,我不明白为什么他们要添加$pdo。我以为那应该是我的联系,但我把它设为$con当我改变$pdo到$con我仍然得到相同的截断在echo 'sup 2';

Statement bindParam方法通过引用接受第二个参数。只有变量可以通过引用传递。

解决方案是将要绑定的参数赋值给变量:

$stmt = $pdo->prepare($sql);
$title = $_POST['title'];
$content = $_POST['content'];
$category = 'City Secrets';
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':content', $content, PDO::PARAM_STR);
$stmt->bindParam(':category', $category, PDO::PARAM_STR);
$stmt->execute();

这是上面问题的正确工作代码。

$stmt->bindParam

改为

 $stmt->bindValue 

增加了DB连接的connection.php文件。

<?php                           
require_once( 'connection.php' );
$sql = "INSERT INTO blogData(
            title,
            content,
            category) 
            VALUES ( 
            :title, 
            :content, 
            :category)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);       
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR); 
$stmt->bindValue(':category', 'City Secrets', PDO::PARAM_STR);
$stmt->execute(); 
 header('location: http://www.website.com');
?>