首页 > 解决方案 > 如何使用从数据库导入的值

问题描述

嘿,这里的每个人都是我的问题。下面的代码从我的数据库中获取数据并将其显示在输入字段和按钮中。我希望它的方式是,如果我单击按钮,它应该获取值(从数据库导入)。但我面临的问题是所有输入和按钮都具有相同的 id,所以它只捕获第一个按钮的值(或者我认为)。我怎样才能使我点击的每个按钮都有自己的单独值。

    <?php  
    $dbcon=mysqli_connect("localhost","root","");  
    mysqli_select_db($dbcon,"codex"); 
    require('config/server.php');
    ?>
    <table class="table table-striped"> 
    <th>ID</th>  
     <?php  
    $view_users_query="select * from users";//select query for viewing 
     users.  
    $run=mysqli_query($dbcon,$view_users_query);//here run the sql 
    query.
    while($row=mysqli_fetch_array($run))//while look to fetch the result 
    and store in a array $row.  
    { 
    ?>    

    <!--here showing results in the table -->

    <form id="loginForm" method="" action="" novalidate>
    <tr>
    <div class="panel2"> 
    <main class="content">

    <td><input name="hanis" id="hanis" type="text" value="<?php echo 
    $row['email']?>"  autofocus /></td>

    <td><button type="button" class="btn btn-success btn-block" 
    name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo 
    $row['email']?>" ><?php echo $row['email']?></button><</td>

    </main></div>
    </div>
    </div>
    </form>
    <?php } ?>
    </tr>


    <script type="text/javascript">

    function hanisdata() {
    var hanis=$("hanis").val();

    alert(hanis); 
    // AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "hanis.php",
        data: {hanis:hanis},
        dataType: "JSON",
        success: function(data) {
         $("#message").html(data);
        $("p").addClass("alert alert-success");
        },
        error: function(err) {
        alert(err);
        }
       });

        }

       </script>

标签: phpjqueryhtmlmysqlajax

解决方案


注意:-不要对元素使用相同的 id

您可以通过使用 onclick 函数传递 this 来获取值,例如onclick="hanisdata(this)"

例子

<button type="button" class="btn btn-success btn-block" 
    name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo 
    $row['email']?>" ><?php echo $row['email']?></button>

然后您可以在 js 中获取特定元素,然后可以在下面的示例中找到父元素并搜索输入字段。

JS代码

<script type="text/javascript">

 function hanisdata(el) {
    var hanis=$(el).parent().find("input").val();

    alert(hanis); 
    // AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "hanis.php",
        data: {hanis:hanis},
        dataType: "JSON",
        success: function(data) {
         $("#message").html(data);
        $("p").addClass("alert alert-success");
        },
        error: function(err) {
        alert(err);
    }
  });

 }

</script>

推荐阅读