从一个文档提交HTML / PHP / MySQL中的表单并在另一个文档中显示结果

时间:2016-08-07 19:32:14

标签: php html mysql pdo html-form-post

我创建了一个由PHP / MySQL支持的HTML <form>,允许用户输入一些信息,然后(应该)通过<form>提交<input type="submit" value="Submit" name="submit" />后发送/存储输入的数据}。 <form>(应该)通过PHP将用户输入的日期连接并存储到MySQL数据库中。然后,PHP支持结果页面上显示的响应,该响应与HTML <form>所在的页面不同。

这是我最后一点没有任何错误,但也没有达到在另一页上显示结果页面的理想解决方案:

HTML <form>

<form action="pdotest/test.php" method="post">
  <fieldset>
    <label for="firstname">Input 1: <input type="text" name="firstname" id="firstname" /></label>
    <label for="lastname">Input 2: <input type="text" name="lastname" id="lastname" /></label>
    <label for="email">Input 3: <input type="text" name="email" /></label>
  </fieldset>
  <input type="submit" value="Submit" name="submit" />
</form>

PHP / MySQL处理:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDBPDO";


try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

结果页面:

<?php

echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator { 
    function __construct($it) { 
        parent::__construct($it, self::LEAVES_ONLY); 
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() { 
        echo "<tr>"; 
    } 

    function endChildren() { 
        echo "</tr>" . "\n";
    } 
} 

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

0 个答案:

没有答案