如何使用sql查询从表单文本框中自动获取数据

时间:2019-07-11 13:10:38

标签: php mysql pdo

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

我设法创建了将数据插入员工和证书的表格,但是当尝试创建用于学习的表格时,我碰壁了。

学习表仅使用int和date,我希望学习记录的表单更加用户友好。

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

certificateid
employeeid
datepassed
dateelapsed

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

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

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

    <?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子句来生成Employee ID和证书ID。

This is my form. i want to be able to enter name and certificate name and it automatically input the id's

Code Error shown in console

Code for form

PHP code for the variables

1 个答案:

答案 0 :(得分:1)

您的代码中有一些问题需要我们加以研究:

绑定变量

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

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

Named placeholders的形式应为::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>