PDO一次更新两个表

时间:2014-05-09 12:39:46

标签: php

我正在尝试在提交表单时一次更新两个表。 http://pastebin.com/ctmaWWN8

除了更新 article_cat 表格外,我还需要更新 article_posts 表格。 在 article_posts 表中,我需要将 cat 设置为我在表单中输入的内容。

UPDATE article_posts SET cat=:cat WHERE cat=:cat

我想这样的东西,但我不知道如何将它们组合在一起!

这是我的PHP代码:

if (isset($_POST['submit'])) {

$cat = $_POST['cat'];
$name = $_POST['name'];

$sqlInsert = 'UPDATE article_cat SET cat=:cat, name=:name WHERE id=:id';
$preparedStatement = $db->prepare($sqlInsert);
$preparedStatement->execute(array(':cat' => $cat, ':name' => $name, ':id' => $id));

if (empty($name)) {
// do something
    echo'<div class="alert-box error"><span>error: </span>Categorys name field is Empty!</div>';
    }
    elseif (empty($cat)) {
        echo'<div class="alert-box error"><span>error: </span>Categorys short name field is Empty!</div>';
    }
    else {



    if ($preparedStatement->execute())
{
  echo'<div class="alert-box success"><span>success: </span>Category Updated!</div>';
}
// If execution failed then ->
else
{

 echo'<div class="alert-box error"><span>error: </span>Something went wrong while updating Category :/ ! Please try again.</div>';
}



    }

}

1 个答案:

答案 0 :(得分:0)

您的代码应该成为此代码,并确保在第二个语句中替换占位符值。

if (isset($_POST['submit'])) {

$cat = $_POST['cat'];
$name = $_POST['name'];

// first    
$sqlInsert = 'UPDATE article_cat SET cat=:cat, name=:name WHERE id=:id';
$preparedStatement = $db->prepare($sqlInsert);

// second
$sqlInsert = 'UPDATE article_posts SET cat=:cat WHERE cat = :_cat';

$preparedStatement->execute(array(':cat' => $cat, ':name' => $name, ':id' => $id));
$preparedStatement->closeCursor();

if (empty($name)) {
    echo'<div class="alert-box error"><span>error: </span>Categorys name field is Empty!</div>';
} elseif (empty($cat)) {
        echo'<div class="alert-box error"><span>error: </span>Categorys short name field is Empty!</div>';
} else {
    // second
    $preparedStatement = $db->prepare($sqlInsert);

    // second query statement
    if ($preparedStatement->execute(array(':cat' => 'set-your-cat', ':_cat' => 'where-clause'))) {
        $preparedStatement->closeCursor();

        echo'<div class="alert-box success"><span>success: </span>Category Updated!</div>';
    } else {
        echo'<div class="alert-box error"><span>error: </span>Something went wrong while updating Category :/ ! Please try again.</div>';
    }
  }

}