首页 > 解决方案 > 如何使用 sql 查询从表单文本框中自动获取数据

问题描述

我正在为我的公司建立一个培训矩阵系统,我有三张表,一张用于员工,一张用于当前证书,一张用于输入记录。

我已经设法创建表格以将数据插入到员工和证书中,但是在尝试为学习创建表格时,我碰壁了。

学习表只使用整数和日期,我希望我的学习记录表格更加用户友好。

目前,我使用这些表单元素

certificateid
employeeid
datepassed
dateelapsed

我想在带有 LIKE 子句的查询中添加certificatename/ 。employeename我已经尝试过了,但没有得到我想要的结果,因为我无法让表单框将结果传递给查询。

请帮助或指出我正确的方向。

我尝试在查询中创建一个变量,然后将其绑定到变量并添加到表单文本名称中,但它似乎没有接受它。

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    // user always
    session_start();
    // Redirect if not logged in
    if (!isset($_SESSION['loggedin'])) {
        header('Location: index.html');
        exit();
    }
    //include Header & db Connection
    include ("templates/header.php");
    require ("connect-db.php");

    if(isset($_POST['AddLearn'])){

        //Retrieve the field values from our learning form.
        $CertificateID = !empty($_POST['CertificateID']) ? trim($_POST['CertificateID']) : null;
        $CertificateName = !empty($_POST['CertificateName']) ? trim($_POST['CertificateName']) : null;
        $EmployeeID = !empty($_POST['EmployeeID']) ? trim($_POST['EmployeeID']) : null;
        $Name = !empty($_POST['Name']) ? trim($_POST['Name']) : null;
        $DatePassed = !empty($_POST['DatePassed']) ? trim($_POST['DatePassed']) : null;
        $DateElapsed = !empty($_POST['DateElapsed']) ? trim($_POST['DateElapsed']) : null;

       $sql = "INSERT INTO learning (CertificateID, EmployeeID, DatePassed, DateElapsed) VALUES (:CertificateID, :EmployeeID, :DatePassed, :DateElapsed)";

       $sql2 = "SELECT EmployeeID FROM employee WHERE Name Like '%$Name%' ";

       $sql3 = "SELECT CertificateID FROM certificate WHERE CertificateName LIKE '%$CertificateName%' ";

            $stmt = $dbCon->prepare($sql);
            $stmt2 = $dbCon->prepare($sql2);
            $stmt3 = $dbCon->prepare($sql3);

           //Bind our variables.
            $stmt->bindValue(':CertificateID', $CertificateID);
            $stmt->bindValue(':EmployeeID', $EmployeeID);    
            $stmt->bindValue(':DatePassed', $DatePassed);
            $stmt->bindValue(':DateElapsed', $DateElapsed);

            //secondry binds for stmt2-3

            $stmt2->bindValue(':Name', $Name);

            $stmt3->bindValue(':CertificateName', $CertificateName);

            //Execute the statement
            $result = $stmt->execute();
            $result2 = $stmt2->execute();
            $result3 = $stmt3->execute();



        //If the process is successful.
        if($result){

          echo  'Record Added';
       }else
       {
           echo 'No record was added due to mistakes';
       }
    }

    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Add New Learning Record</title>
        </head>
        <body>
            <div class="adding">
            <h1>Add New learning Record</h1><br>
                 <form action="newlearn.php" method="post">

                <label for="CertificateID">Certificate ID</label>
                <input type="text" id="CertificateID" name="CertificateID"><br>

                <label for="CertificateName">Certificate Name</label>
                <input type="text" id="CertificateNameID" name="CertificateNameID"><br>

                <label for="EmployeeID">Employee ID</label>
                <input type="text" id="EmployeeID" name="EmployeeID"><br>

                <label for="Name">Name</label>
                <input type="text" id="NameID" name="NameID"><br>

                <label for="DatePassed">Date Passed</label><center>(Date in YYYY.MM.DD)</center>
                <input type="text" id="DatePassed" name="DatePassed"><br>

                <label for="DateElapsed">Date Elapsed</label><center>(Date in YYYY.MM.DD)</center>
                <input type="text" id="DateElapsed" name="DateElapsed"><br>

                <input type="submit" name="AddLearn" value="Add New Record"></button>
            </form>
        </div>
    </html>

我希望通过从两个相关表中抓取数据,使用 like 子句生成员工 ID 和证书 ID。

这是我的表格。我希望能够输入姓名和证书名称,它会自动输入 id

控制台中显示的代码错误

表格代码

变量的 PHP 代码

标签: phpmysqlpdo

解决方案


您的代码存在一些问题,我们必须调查:

绑定变量

我将只选择其中一个 SQL 查询,但同样适用于其余查询:

$sql2 = "SELECT EmployeeID FROM employee WHERE Name Like '%$Name%' ";
// ...
$stmt2->bindValue(':Name', $Name);

命名占位符应采用以下形式::Name因此您的查询应如下所示(通配符运算符使其不太直观):

$sql2 = "SELECT EmployeeID FROM employee WHERE Name Like CONCAT('%', :Name, '%')";

不从 SELECT 语句中获取

$sql2 = "SELECT EmployeeID FROM employee WHERE Name Like LIKE CONCAT('%', :Name, '%')";
$stmt2->bindValue(':Name', $Name);
$result2 = $stmt2->execute();

您执行该语句,但不要在代码中的任何地方使用结果。相反,您将获取一行并将其显示在表单中的某个位置:

if ($stmt2->rowCount() > 0) {
  $row= $stmt2->fetch(PDO::FETCH_ASSOC);
  $employeeId= $row['EmployeeID'];
}

使用 NULL 作为默认值

也只是在一个示例行中指出它:

$DatePassed = !empty($_POST['DatePassed']) ? trim($_POST['DatePassed']) : null;
// ...
$sql = "INSERT INTO learning (CertificateID, EmployeeID, DatePassed, DateElapsed) VALUES (:CertificateID, :EmployeeID, :DatePassed, :DateElapsed)";
$stmt = $dbCon->prepare($sql);
$stmt->bindValue(':DatePassed', $DatePassed);
$result = $stmt->execute();

如果您的数据库表“学习”允许在字段中插入 NULL,您可能会在“CertificateID”、“EmployeeID”等字段中创建许多包含 NULL 值的错误行。相反,我建议:

  1. 在客户端检查字段的完整性
  2. “早点返回”:不要尝试插入一条如果缺少必填字段很可能会失败的记录,而是在服务器端引入字段检查。就像是:
if (empty($_POST['CertificateID'] || empty($_POST['EmployeeID']) || empty($_POST['DatePassed'])) {
  print "Mandatory fields are missing. Please try again.";
} else {
  // continue with inserting data.
}

使用 LIKE 而不是检查相等性

我还想知道为什么您需要使用 LIKE 子句而不是检查是否相等?与其让用户手动输入员工姓名,不如创建一个包含员工姓名的 SELECT,然后使用WHERE Name = :Name. 这对用户更友好。

更新1:

您的表单目前有多余的 - 更好地说容易出错 - 字段:证书 ID 和姓名/员工 ID 和姓名。如果有人输入的证书 ID 与证书名称不符,则您的数据库中的数据将不正确。相反,如评论中所述,您将使用选择列表。

首先,为您的 SELECT 加载所需的数据:

$sqlEmployees = "SELECT EmployeeID, Name FROM employee ORDER BY name";
$stmtEmployees = $dbCon->prepare($sql2);
$arrEmployees= array();
if ($stmtEmployees->execute()) {
  $arrEmployees = $stmtEmployees->fetchAll(PDO::FETCH_ASSOC);
}

$sqlCertificates = "SELECT CertificateID, CertificateName FROM certificate ORDER BY CertificateName";
$stmtCertificates = $dbCon->prepare($sql2);
$arrCertificates= array();
if ($stmtCertificates->execute()) {
  $arrCertificates = $stmtCertificates->fetchAll(PDO::FETCH_ASSOC);
}

然后,将值作为表单的一部分输出,同时去掉冗余字段:

<form action="newlearn.php" method="post">

    <label for="CertificateID">Certificate</label>
    <select name="CertificateID" id="CertificateID">
    <?php
      for($i=0;$i<count($arrCertificates);$i++) {
         $row= $arrCertificates[$i];
      ?>
      <option value="<?= $row['CertificateID'] ?>"><?= $row['CertificateName'] ?></option>
      <?php
      }
    ?>
    </select>

    <label for="EmployeeID">Employee</label>
    <select name="EmployeeID" id="EmployeeID">
    <?php
      for($i=0;$i<count($arrEmployees);$i++) {
         $row= $arrEmployees[$i];
      ?>
      <option value="<?= $row['EmployeeID'] ?>"><?= $row['Name'] ?></option>
      <?php
      }
    ?>
    </select>

    <label for="DatePassed">Date Passed</label><center>(Date in YYYY.MM.DD)</center>
    <input type="text" id="DatePassed" name="DatePassed"><br>

    <label for="DateElapsed">Date Elapsed</label><center>(Date in YYYY.MM.DD)</center>
    <input type="text" id="DateElapsed" name="DateElapsed"><br>

    <input type="submit" name="AddLearn" value="Add New Record"></button>
</form>

推荐阅读