猿问

通过 PHP foreach 循环按钮将数据提交到 mysql 数据库的单行

我通过使用 php 的foreach构造循环在网站上显示 mysql 表,例如:


<?php foreach($bills as $bills): ?>

   <tr>

      <td><?= $bills->column1; ?></td>

      <td><?= $bills->valid; ?></td>

      <td><?= $button; ?></td>

   </tr>

<?php endforeach; ?>

名为 的列valid设置为varchar(1),因此它的值是y或n来定义账单是有效还是无效。


默认情况下,命名列的每一行都valid设置为n- 通过单击一行的按钮,我想将valid特定行的值设置为,y但我对如何以正确的方式传递数据有点迷茫。


该$button变量包含以下 html 代码:


<form id="submit">

   <button type="submit">Valid</button>

</form>

单击该按钮运行下面的 ajax 脚本:


<script>

   $('#submit').click(function() {

      $.ajax({

         url: 'connect.php',

         type: 'POST',

         data: null,

         success: function(msg) {

            alert('Success ');

         }

      });

   });

</script>

connect.php 运行以下代码:


<?php include('../config.php') ?>


<?php 

   $query = $pdo->prepare("UPDATE bills SET valid='y'");

   $query->execute();

?>

我的猜测是我必须通过 ajax 的data选项发送一个变量,然后在 mysql 查询中调用它,比如


UPDATE bills SET valid='y' WHERE variablefromajax = id

但正如我上面提到的,我对如何检查单击了哪个特定按钮然后传递该信息有点无能为力。


提前感谢您的帮助。


慕村9548890
浏览 126回答 2
2回答

扬帆大鱼

您可以使用 get 请求传递数据。喜欢:<script>&nbsp; &nbsp;$('#submit').click(function() {&nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url: 'connect.php?ifvalid=y',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data: null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: function(msg) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Success ');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp;});</script>在您的 php 文件中,您可以使用它,$_REQUEST['ifvalid']然后您可以有条件地在数据库中进行更改。

鸿蒙传说

在这种情况下,由于您计划有多个按钮,请确保每个按钮都有两个 HTML 属性:data-row-id="<ID of the row>"特定类,如 class="row-submitter"然后,稍微改变你的逻辑来跟踪类点击,而不是 ID:$('.row-submitter').click(function() {&nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url: 'connect.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data: null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: function(msg) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Success ');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp;});由于按钮的属性上还有 ID 数据,您现在可以说:$('.row-submitter').click(function() {&nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url: 'connect.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data: "id="+$(this).data('row-id')+'&value=newvalue',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: function(msg) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Success ');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp;});并像使用它们一样&nbsp; &nbsp;$query = $pdo->prepare("UPDATE bills SET valid='".$_POST['value']."' where id=".$_POST['id']."");
随时随地看视频慕课网APP
我要回答