【问题标题】:update two tables rows by id through transaction通过事务按id更新两个表行
【发布时间】:2018-02-07 07:07:43
【问题描述】:

如何选择两个表并通过 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();

【问题讨论】:

  • 用 prep stmts 试过,但 id 不能作为参数工作 ...这是为什么呢?准备语句的尝试在哪里?

标签: php sql join parameters


【解决方案1】:

你写的SQL可能没有收集到,你必须先在SQL客户端运行它来测试SQL语法。

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

UPDATE movies m
INNER JOIN category c ON
    m.id = m.id
SET title=?, director=?, year=?, genre =?
WHERE id =?

顺便说一句,inner join 可能没有必要,看你的需求。

同样,您必须先测试结构,并且只有在收集到之后再将其嵌入到其他语言中。

已编辑

如何在 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

【讨论】:

  • 好吧,问题并不是真正的 sql 语法,而是语句参数:我想加入表 id 并更新 id 为 (?) ($ID) 的行,还添加其他参数.
  • wekk 如何在终端中进行 prep stmt? prep stmt 查询是针对 php
猜你喜欢
  • 2022-01-09
  • 2018-01-14
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2018-07-10
相关资源
最近更新 更多