首页 > 解决方案 > 在数据库中查找不成功后,如何用已插入的文本替换表单?

问题描述

我在 Participate.php 文件中有代码,它有一个表单:

<form method="post" action="input.php" id="Form">
            <input type="text" class="form-control" name="txtName" maxlength="20" required style="margin-bottom:20px"> 
            <input type="email" class="form-control" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
            <input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
        </form>

提交失败后(我检查插入的邮件是否已存在于数据库中),如果不存在,我想重新填写表单的值。这是 input.php 代码:

<?php

$name = $_POST['txtName']; 
$mail = $_POST['txtEmail']; 
$description = $_POST['txtDescription'];
$connect = new PDO("mysql:host=4*****3;dbname=3*****b", "3***b", "****");
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

$q=$connect->prepare("SELECT mail FROM konkurs WHERE mail LIKE (?)");
$q->bindValue(1, $mail);
$q->execute();
$row_cnt = $q->rowCount();
    if($row_cnt == 0){
        $query = $connect->prepare("insert into konkurs(name,mail,description)
        values(?, ?, ?)");
        $query->bindValue(1, $name);
        $query->bindValue(2, $mail);
        $query->bindValue(3, $description);
        try {
            $query->execute();
            echo ("<script LANGUAGE='JavaScript'>
            window.alert('Sent.');
            window.location.href='index.html';
            </script>");
            exit;
            } catch (PDOException $e) {
            die($e->getMessage());
            } 
    } else {
        echo ("<script LANGUAGE='JavaScript'>
            window.alert('This mail already exist.');
            window.location.href='Participate.php';
            document.getElementById('txtName').value = 'nothing';
            </script>");
        }

?>

问题是它在失败后重定向到 Participate.php。但它不会重新填写表格。

标签: javascriptphphtml

解决方案


首先,您必须更改您的 HTML 以包含该id属性,例如:

<form method="post" action="input.php" id="Form">
    <input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px"> 
    <input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
    <input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>

然后,您必须将您的逻辑移动到与表单容器(此处)相同的文件中Participate.php,并删除失败的重定向。否则,您将看不到任何结果,因为重定向会阻止进一步的 JavaScript 代码运行。

// Updated to prevent syntax errors with multiline strings
echo "<script>"
     . "window.alert('This mail already exist.');"
     . "document.getElementById('txtName').value = 'nothing';"
     . "</script>";

推荐阅读