通过事务以id更新两个表行

时间:2018-02-07 07:07:43

标签: php sql join parameters

如何选择两个表并通过id连接它们以通过事务进行更新? 我尝试使用prep stmts,但id不会作为参数工作.... 交易能做到吗?

// submit
if (isset($_POST['submit']))
  {
  // Edit ID
  if (isset($_GET['edit'])) 
  $ID = $_GET['edit'];       
  // form input 
  if (isset($_POST['title'], $_POST['director'], $_POST['year'], $_POST['genre'])) 
  $title = $_POST['title'];
  $director = $_POST['director'];
  $year = $_POST['year'];
  $category = $_POST['genre'];      

  // required
  if ( $title == '' || $director == '' || $year == '' ||$category == '')
   {
   // generate error message
   $error = 'Fält saknas!';
   // if either field is blank, display the form again
   renderForm($category, $title, $director, $year, $error);
   }
  else {  
  // Edit 
  // auto turn off
   mysqli_autocommit($conn,FALSE);
   // values
   mysqli_query($conn, "INSERT INTO movies (title, director, year) 
   VALUES ('$title', '$director', '$year') WHERE ID = '$ID'");
   mysqli_query($conn, "INSERT INTO category (category) 
   VALUES ('$category') WHERE ID = '$ID'");
   // Commit transaction
   mysqli_commit($conn);

     echo "<div class='receipt'>Register ".$ID." uppdaterat.<br>
     <a href='index.php'>Gå tillbaka</a> </div>";
             }
} $conn->close();

1 个答案:

答案 0 :(得分:0)

您的写入可能不会收集的SQL,您必须首先在SQL客户端中运行它以测试SQL语法。

如果你使用MySQL,收集方式必须是这样的:

UPDATE movies m
INNER JOIN category c ON
    m.id = m.id
SET title=?, director=?, year=?, genre =?
WHERE id =?
顺便说一句,inner join可能没有必要,看看你的需求。

同样,您必须首先测试结构,并且只有在收集结构然后将其嵌入其他语言时才会进行测试。

<强> EDITED

如何在MySQL客户端中使用预准备语句:

mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql> SET @a = 3;
mysql> SET @b = 4;
mysql> EXECUTE stmt1 USING @a, @b;
+------------+
| hypotenuse |
+------------+
|          5 |
+------------+
mysql> DEALLOCATE PREPARE stmt1;

来自https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html