2

我正在向数据库中插入几个字段,这是我可以做到的。我采用了一个将数据插入表“AFTER INSERT”事件的触发器。

<html>
<body>

<?php
$id=$_POST['id'];
$a=$_POST['id'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$city=$_POST['city'];

$con=mysqli_connect('127.0.0.1:3306' ,'root','root','my_db');
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql1="select * from table2";

$result = mysqli_query($con,$sql1);
echo "<table border='1'>

<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))

{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>"; 

$sql3 = "在 temp2 上插入每行开始插入临时值后创建触发器 MysqlTrigger (new.id,new.fname,new.lname,new.city,new.city);"; mysqli_query($con,$sql3);

$sql5="INSERT INTO temp2 (id,fname, lname, city)
VALUES
('$_POST[id]','$_POST[fname]','$_POST[lname]','$_POST[city]')";
mysqli_query($con,$sql5);



echo "1 record added";

//--------------- Trigger started ------------------

print "<h2>CREATE MySQL Trigger In PHP</h2>";
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Status</th>
</tr>";
$sql4="select * from temp";
$res = mysqli_query($con,$sql4);
while($row = mysqli_fetch_array($res,MYSQLI_ASSOC))

{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['stat'] . "</td>";
echo "</tr>";
}
echo "</table>"; 

mysqli_close($con);

?>
</body>
</html>

这成功地将数据插入到 temp2 表中,但触发器中的事件不会对 temp 表进行任何更改。

我在哪里犯错?

4

1 回答 1

2

来自mySQL 手册

delimiter |

CREATE TRIGGER testref BEFORE INSERT ON test1
  FOR EACH ROW BEGIN
    INSERT INTO test2 SET a2 = NEW.a1;
    DELETE FROM test3 WHERE a3 = NEW.a1;
    UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
  END;
|

delimiter ;

你错过了分隔符和触发器的结束


为什么您要尝试使用 php 创建触发器?你不能在 MySQL Workbench 上用 phpMyAdmin 创建它吗?触发器应该存在于数据库中......如果它不应该是永久的,你应该把它放在你的 php 代码的末尾......

于 2013-07-03T12:15:04.507 回答