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

Php 如何使用sql查询从表单文本框自动获取数据,php,mysql,pdo,Php,Mysql,Pdo,我正在为我的公司建立一个培训矩阵系统,我有三个表,一个用于员工,一个用于当前证书,另一个用于输入记录 我已经设法创建了表格,以便向员工和证书插入数据,但在尝试创建学习表格时,我遇到了麻烦 学习表只使用int和dates,我希望我的学习记录表单更加用户友好 目前,我已将其用于这些表单元素 certificateid employeeid datepassed dateelapsed 我想添加certificatename/employeename,它将位于带有LIKE子句的查询中。我已经尝试过了

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

我已经设法创建了表格,以便向员工和证书插入数据,但在尝试创建学习表格时,我遇到了麻烦

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

目前,我已将其用于这些表单元素

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>

您的代码中存在一些问题,我们必须研究:

绑定变量 我只选择其中一个SQL查询,但对其余的SQL查询也同样适用:

$sql2 = "SELECT EmployeeID FROM employee WHERE Name Like '%$Name%' ";
// ...
$stmt2->bindValue(':Name', $Name);
应采用以下格式:
:Name
,因此您的查询应如下所示(通配符运算符使其不那么直观):

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

if ($stmt2->rowCount() > 0) {
  $row= $stmt2->fetch(PDO::FETCH_ASSOC);
  $employeeId= $row['EmployeeID'];
}
使用空值作为默认值 另外,仅在一个示例行中指出:

$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();
如果数据库表“learning”允许在字段中插入空值,则可能会在“CertificateID”、“EmployeeID”等字段中创建许多包含空值的错误行。 相反,我建议:

  • 检查客户端上的字段是否完整
  • “Return early”:与其尝试插入一条记录(如果缺少必填字段,该记录很可能会失败),不如在服务器端引入字段检查。比如:
  • 使用LIKE而不是检查是否相等 我还想知道为什么你需要使用LIKE子句而不是检查是否相等?不要让用户手动输入员工姓名,而是创建一个包含员工姓名的选择框,然后使用
    WHERE name=:name
    。这对用户更友好

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

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

    $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>
    
    
    证明书
    受雇者
    通过日期(年月日)
    
    已过日期(以YYYY.MM.DD为单位的日期)

    您好,SaschaM78,谢谢您的宝贵建议。我不确定它是否需要一美元或一美元,但现在已经改变了。我还将它从like子句更改为where=。我面临的最初问题是,在提交之前,让姓名框自动填写certificaeName live的员工id和certificateID,因为我想让它更方便用户Hi@MichaelBroderick,欢迎您。当前的主要问题是,
    $stmt2
    $stmt3
    仅在您刚刚发布了数据的情况下才会执行(这意味着您刚刚尝试保存数据)。因此,在提交学习之前,您需要更改代码以获取数据。我最近刚开始学习,对此我一无所知。我曾考虑将学习记录页面更改为一个包含所有名称的下拉列表,然后使用从下拉框创建的变量添加表单,但我不确定。不知道该去哪里,甚至不知道该搜索什么。任何帮助都可能是错误的apprecisted@MichaelBroderick我很久以前就去过那里了,但我记得我自己是多么无知。我建议:1)加载员工列表,并用它建立一个下拉列表2。)认证也一样。然后使用这些作为表单的基础。我还建议始终使用数据库内部ID来检索数据,而不是使用基于文本的WHERE子句,这样会比较慢。您的选择列表应将ID作为其值,并将名称作为选项的内容。然后使用ID查询数据库。祝你好运我认为是数据库内部ID,你是说EmployeeID和CertificateID,可能是你在
    if(isset($\u POST['AddLearn'])中创建了两个变量吗{
    condition?如果是,则只有在将学习内容保存到数据库后,才会填充这些语句。您必须移动这些语句,以便它们独立于INSERT语句执行。
    if (empty($_POST['CertificateID'] || empty($_POST['EmployeeID']) || empty($_POST['DatePassed'])) {
      print "Mandatory fields are missing. Please try again.";
    } else {
      // continue with inserting data.
    }
    
    $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>