首页 > 解决方案 > 每次单击按钮然后将其用于查询时如何获取 php 变量?

问题描述

每次单击按钮时,我都会尝试获取 $row['username'] ,以便在查询中使用它。但只显示第一个数组。我想使用jquery,但我对此知之甚少。

<?php
  $query = $con->query("SELECT * FROM account WHERE acc = 'agency'");
  while($row = mysqli_fetch_array($query))
  {
    echo $row['username'];
  ?>
    <button data-target="#select" data-toggle="modal">Select</button>
<?php } ?>


  <div class="modal" id="select">
  <?php
    $query = $con->query("SELECT * FROM sample WHERE username = ".$row['username']."");

  ?>

标签: phpjqueryhtml

解决方案


<button id="select"
        class="selectUser"
        data-username="<?php echo $row['username']; ?>"
        data-toggle="modal"
        data-target="#select">Select</button>

我拿了您在评论中添加的 html,并为其添加了一个类。现在你需要做的就是为它创建你的javascript绑定。

//find all the buttons with the selectUser class and bind a click handler to them
$('.selectUser').on('click', function(e){
    //turn the element into a jQuery object so we can use jQuery methods
    var $selectUser = $(this);
    //log the username data attribute from the button
    console.log($selectUser.data('username'));

    //you could also get the attribute without jQuery
    console.log(this.getAttribute('data-username'));
});

推荐阅读