php - 如何使用从数据库导入的值
问题描述
嘿,这里的每个人都是我的问题。下面的代码从我的数据库中获取数据并将其显示在输入字段和按钮中。我希望它的方式是,如果我单击按钮,它应该获取值(从数据库导入)。但我面临的问题是所有输入和按钮都具有相同的 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>
解决方案
注意:-不要对元素使用相同的 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>
推荐阅读
- python - 如何打印列表中的最大数字,该列表旁边还有其他元素在同一字符串中
- android - 如何修复冻结同步 - Gradle:下载 maven-metadata.xml
- reactjs - create-react-app 后缺少依赖项
- c# - ASP.NET 每次都在加载和卸载程序集,这需要花费大量时间
- node.js - 我正在做 Oath facebook 登录,但每次 findorcreate 都会出错
- c# - EF Core - 通过复合键获取实体
- spring - 我没有收到 WebSocket 消息 (SimpMessagingTemplate)
- java - 我的应用程序在打开时崩溃,我认为这是由于 swisseph.jar
- sql - 遍历 PostgresSQL 中的一个 json 字段
- typo3 - 如何通过 TypoScript 获取 HMENU 项目的“级别标题”?