PDO UPDATE查询无法正常工作

时间:2013-03-24 13:04:17

标签: php mysql pdo mysqli

有问题的代码是这样的:

if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_POST['id'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
}
if (empty($title) or empty($content) or empty($id)) {
        $error = 'All fields are required!';
} else {

    try {

    $query = $pdo->prepare("UPDATE articles SET     article_title = ?, article_content = ? WHERE article_id = ? ");


    $query->bindValue(1, 'title'); 
    $query->bindValue(2, 'content'); 
    $query->bindValue(3, 'id'); 

    $query->execute();  

header('Location: index.php'); } catch (PDOException $e) {
print_r($e->errorInfo);
die(); } } }    

它没有给我任何错误,表格也没有更新。

P.S。我对PHP一般都很陌生,所以如果我的错误有点琐碎,请耐心等待,我只是没有其他人可以问。

2 个答案:

答案 0 :(得分:2)

$query->bindValue(1, 'title'); 
$query->bindValue(2, 'content'); 
$query->bindValue(3, 'id'); 

bindValue的第二个值应该是,而不是值的名称,例如;

$query->bindValue(1, $title); 
$query->bindValue(2, $content); 
$query->bindValue(3, $id, PDO::PARAM_INT); 

答案 1 :(得分:2)

如果您是PHP新手,那么我建议您尝试使用占位符(?)执行查询的替代方法,因为它更简单。

首先设置连接。

try {
  # First let us connect to our database 
  $db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", []); 
 } catch(\PDOException $e){
   echo "Error connecting to mysql: ". $e->getMessage();
 }

# And pass optional (but important) PDO attributes
$db->setAttribute(
   PDO::ATTR_EMULATE_PREPARES => false, 
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
 ); 

现在调用prepare / execute方法,如:

$stmt = $db->prepare("
        UPDATE articles 
        SET article_title = ?, article_content = ? 
        WHERE article_id = ?
 ");

 $stmt->execute(array($article_title, $article_content,$article_id));

 if($stmt->rowCount()) {
   echo 'success';
 } else {
   echo 'update failed';
 }