使用SQL和PHP在实体中编辑多个记录

时间:2018-07-22 07:08:53

标签: php mysql sql

我是PHP的新手,似乎正在学习一个半生半熟的教程。令人难以置信的是,现在我很想解决这个问题。

我正在尝试使用一种表单提交来更新多个实体中的多个记录。我的PHP函数如下。

function updateFixture() {

  global $server, $db, $dbUser, $dbKey, $message;

  try {
    $conn = new PDO("mysql:host=" . $server . ";dbname=" . $db, $dbUser, $dbKey);
    $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = $conn -> prepare("UPDATE Date SET date=:date WHERE dateID=:dateID");

    $sql -> bindValue(":dateID", $_POST["dateID"]);
    $sql -> bindValue(":date", $_POST["date"]);

    $sql = $conn -> prepare("UPDATE Score SET homeScore=:homeScore1, awayScore=:awayScore1 WHERE scoredID=:scores1");

    $sql -> bindValue(":scores1", $_POST["scores1"]);
    $sql -> bindValue(":homeScore1", $_POST["homeScore1"]);
    $sql -> bindValue(":awayScore1", $_POST["awayScore1"]);

    $sql = $conn -> prepare("UPDATE Score SET homeScore=:homeScore2, awayScore=:awayScore2 WHERE scoredID=:scores2");

    $sql -> bindValue(":scores2", $_POST["scores2"]);
    $sql -> bindValue(":homeScore2", $_POST["homeScore2"]);
    $sql -> bindValue(":awayScore2", $_POST["awayScore2"]);

    $sql = $conn -> prepare("UPDATE Score SET homeScore=:homeScore3, awayScore=:awayScore3 WHERE scoredID=:scores3");

    $sql -> bindValue(":scores3", $_POST["scores3"]);
    $sql -> bindValue(":homeScore3", $_POST["homeScore3"]);
    $sql -> bindValue(":awayScore3", $_POST["awayScore3"]);

    $sql = $conn -> prepare("UPDATE Score SET homeScore=:homeScore4, awayScore=:awayScore4 WHERE scoredID=:scores4");

    $sql -> bindValue(":scores4", $_POST["scores4"]);
    $sql -> bindValue(":homeScore4", $_POST["homeScore4"]);
    $sql -> bindValue(":awayScore4", $_POST["awayScore4"]);

    $result = $sql -> execute();

    if ($result) {
      $message = "Customer record was updated";
    } else {
      $message = "The Customer record was not updated";
    }
  }

  catch(PDOException $e) {
    echo "<div class='notification container'><p>An error occured: " . $e -> getMessage() . "</p></div>";
  }

  $conn = null;
}

if (isset($_POST["updateFixture"])) {
  updateFixture($_POST["dateID"]);
}

这似乎与对prepare实体执行的一个Score语句一起很好。当我添加另外三个prepare语句时,就是这个函数失败了。

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要为每个execute()调用prepare(),您只需要在末尾调用一次即可。

所以...

$sql = $conn -> prepare("UPDATE Date SET date=:date WHERE dateID=:dateID");

$sql -> bindValue(":dateID", $_POST["dateID"]);
$sql -> bindValue(":date", $_POST["date"]);

$result = $sql -> execute();

$sql = $conn -> prepare("UPDATE Score SET homeScore=:homeScore1, awayScore=:awayScore1 WHERE scoredID=:scores1");