Jump to content

How can I enable posting form data on to the same page.


Nuzzy

Recommended Posts


<?php
if (isset($_POST['name']) && !empty($_POST['name'])) {
$message = "Your name is " . $_POST['name'];
}
else {
$message = "Please enter a name and click \"Submit\" ";
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<?php echo $message; ?>
<hr/>
<form method="post" action="">
Name <input type='text' name='name' placeholder="Enter your name">
<br/>
<br/>
<input type="submit" name="btnSubmit" value="Submit">
</form>

</body>
</html>

Yes.

 

For the following example to work you would need a database schema called "test" containing a table "person"

CREATE TABLE `person` (
  `id` int(3) unsigned zerofill NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

then a simple example would be

<?php
    // connect to database server
$db = new mysqli(HOST,USERNAME,PASSWORD,'test'); // use your credentials
error_reporting(-1);

    $message = '';

    if (isset($_POST['name']) && !empty($_POST['name'])) {
        // sanitize the input
        $name = $db->real_escape_string($_POST['name']);
        // insert into the database
        $sql = "INSERT INTO person (name) VALUES ('$name')";
        $db->query($sql);
    }
        // list current names from database
    $sql = "SELECT name FROM person";
    $res = $db->query($sql);
        // are there currently any names?
    if ($res->num_rows > 0) {
        $message = '<h3>Current Names</h3>';
        while ($row = $res->fetch_assoc()) {
            $message .= $row['name'] . '<br>';
        }
    }
    
    $message .= "<br>Please enter another name and click \"Submit\" ";


?>
<html>
<head>
<title>Example 2</title>
</head>
<body>
    
    <?php
        echo $message; 
    ?>
    <hr/>
    <form method="post" action="">
        Name <input type='text' name='name' placeholder="Enter your name">
        <br/>
        <br/>
        <input type="submit" name="btnSubmit" value="Submit">
    </form>

</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.