gpt4 book ai didi

php - 将表单与 PHP 脚本链接以从数据库中检索数据

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:47 26 4
gpt4 key购买 nike

我是 PHP 的初学者,我正在尝试弄清楚如何将表单链接到 PHP 脚本。

基本上,我正在创建一个搜索栏,用户可以在其中根据员工 ID 在数据库中搜索员工详细信息。然后脚本会根据 ID 从数据库中检索结果。

代码:

    <form action="results.php" method="get">
Employee ID: <input type="text" name="name"><input type="submit">
</form>
<?php


// connect to the mysql database server
$db = new PDO('mysql:host=localhost:3306;dbname=db_test14;charset=utf8', 'root', 'password');

// Prepare the statement (the basic outline of your query)
$st = $db->prepare('SELECT * from techsols_employee WHERE id = ?');

// Actually execute the query, putting in your id
$st->execute(array($employee_id));

// Get the actual employee details out of the result
$employee = $st->fetch();
?>

希望对此有所帮助。

最佳答案

<form action="results.php" method="GET">
Employee ID: <input type="text" name="name"><input type="submit">
</form>
<?php
if (isset($_GET['name'])) {

//! Some validation and sanitising of the _GET here
$employee_id = $_GET['name'];


// connect to the mysql database server
$db = new PDO('mysql:host=localhost:3306;dbname=db_test14;charset=utf8', 'root', 'password');

// Prepare the statement (the basic outline of your query)
$st = $db->prepare('SELECT * from techsols_employee WHERE id = ?');

// Actually execute the query, putting in your id
$st->execute(array($employee_id));

// Get the actual employee details out of the result
$employee = $st->fetch(PDO::FETCH_ASSOC);
echo $employee['name'];
}
?>

我改变了什么?

  • GET 到 POST ( Difference ) - 在评论返回 _GET 后编辑。
  • $employee_id 等于 _POST
  • 检查你是否通过isset输入
  • 将获取样式更改为 PDO::FETCH_ASSOC

关于php - 将表单与 PHP 脚本链接以从数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com