PHP Saving Form Data Into Database


PHP Saving Form Data Into Database:– In this tutorial you will learn how to store form data into mysql. When user fills out form text field and clicks on submit button; immediately form data is retrieved and executed by php script “connectdbdemo.php” in our below example.

Here we have written _POST method to get input field’s values and then to insert into table name JohnData which we have created in our previous tutorials.

To understand our below example you should learn the simple flow of form.html script.

Example // Simple form.html

<html>
<head>
<style>

.sub {

   font-family:Arial, Helvetica, sans-serif;

   font-size:14px;

   float: left;

   margin-left:30px;

   margin-top:8px;

   margin-bottom:8px;

   width:85%;

}

</style>
</head>
<body>

<form method="post" action="connectdbdemo.php">
<table>
<tr>
<td><label for="fname">First Name</label></td>
<td><input type="text" id="fname" name="fname"/></td>
</tr>
<tr>
<td><label for="lname">Last name</label></td>
<td><input type="text" id="lname" name="lname"/></td><br/>
</tr>
<tr>
<td><label for="email">What is your email address</label></td>
<td><input type="text" id="email" name="email" /></td><br /> 
</tr>
<img src="dog.jpg" width="200" height="175"
alt="My abducted dog Fang." /><br /> 
<tr>
<td><input type="submit" value="Connect Database"  class="sub" /> </td>
</tr>
</table>
</form>
</body>
</html>

Example // Simple connectdbdemo.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employee";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "INSERT INTO JohnData (firstname, lastname, email) VALUES ('$_POST[fname]', '$_POST[lname]', '$_POST[email]')";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
	echo "<br>";
} else {
    echo "Error updating record: " . $conn->error;
}
$sql="DELETE FROM JohnData WHERE id=31";
$sql = "SELECT id, firstname, lastname,email FROM JohnData";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Advertisements

Add Comment

📖 Read More