使用PHP中的按钮填充sql查询的html输入



我有两个带有名称和姓氏的输入,我从数据库中获得所有值​​当按下表格上的按钮时,我希望用数据完成输入。当没有数据可显示时,它应该抛出一个警告。我留下了迄今为止我所做的事情的代码。

<?php
function customersData(){
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store= 1150";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $customers;
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
$data=customersData();
?>
<html>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="ficha">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="ficha">
</div>          
</div>
<button type="submit" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
var btnData = document.getElementById("btnData");
btnData.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>

您可能想要使用Ajax,我添加了JQuery来简化它。
尝试一下,并管理您的id_store变量。

<?php
function customersData($id) {
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
if (!empty($_GET["get_data"])) {
$data = customersData(intval($_GET["get_data"]));
echo json_encode($data);
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
</head>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="lastname">
</div>          
</div>
<button type="button" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
$("#btnData").click(function (ev) {
$.get(window.location.href, {
"get_data": 1150
}, function (result) {
let obj = JSON.parse(result);
$("#name").val(obj.CTE_NAME);
$("#lastname").val(obj.CTE_LASTNAME);
});
});
</script>
</body>
</html>

最新更新