Saturday, February 13, 2016

PHP and SQLite Form Validate Submit and Table Insert


.
PHP and SQLite Form Validate Submit and Table Insert
This tutorial demonstrates the use of form and PHP scripts to obtain new record and save it to the database table.
This tutorial provides two techniques; 1) using two script files ie submitbuddy.php and addbuddy.php or 2) using a single script file ie newbuddy.php
Both techniques produce the same outcome.

0) Starting Up

1) Create form for user to submit new record

The codes below are following HTML5 standards.
They help to validate the data when the user submit the form.
File: submitbuddy.php
<html>
<body>
<form action="addbuddy.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>E-mail: <input type="email" name="email"
        required placeholder="Enter a valid email address"></p>
<p>Photo: <input type="hidden" name="photo">
<input type="file" onchange="previewFile()">
<p><img src="" height="100" alt="Image preview..."></p>
<p><input type="submit" value='Submit' name="submit"></p>
</form>
<script>
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
   reader.addEventListener("load", function () {
     preview.src = reader.result;
    var file = document.querySelector('input[type=file]').files[0];
    document.getElementsByName("photo")[0].value = preview.src;    
   }, false);
  if (file) {
    reader.readAsDataURL(file);
  }
}
</script>
</body>
</html>
OUTCOME.

2) Create script to insert new record into database table

File: addbuddy.html
<?php
function getDB() {
        $dbConnection = new PDO("sqlite:buddies.sdb");
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbConnection;
}
if (isset($_POST['name']) &&
        isset($_POST['email']) &&
                isset($_POST['photo'])){
                        $name=$_POST['name'];
                        $email=$_POST['email'];
                        $photo=$_POST['photo'];
                        try {
                                $DB=getDB();
                            $DB->exec("INSERT INTO tblbuddies (name, email, photo)
                                    VALUES ('$name','$email','$photo')");
                            echo "Data added successfully";            
                            // close the database connection
                            $DB = NULL;                
                        }        
                                catch(PDOException $e){
                            echo 'Exception : '.$e->getMessage();
                        }
}
?>
OUTCOME.
Check that the new record has been added to the database table.

3) Alternative Approach: Single Script File To Display Form and Process Submission

Alternatively, we can put the entire codes into a single script file.
Notice that when the user submit the form, the script calls itself again (ie <?php $_SERVER['PHP_SELF'] ?>) to process the submitted record details.
The PHP codes are placed on top of the HTML codes so that when the script is executed for the first time, the form data is empty and therefore PHP codes are skipped.
File: newbuddy.php
<?php
function getDB() {
        $dbConnection = new PDO("sqlite:buddies.sdb");
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbConnection;
}
if (isset($_POST['submit'])) {
if (isset($_POST['name']) &&
        isset($_POST['email']) &&
                isset($_POST['photo'])){
                        $name=$_POST['name'];
                        $email=$_POST['email'];
                        $photo=$_POST['photo'];
                        try {
                                $DB=getDB();
                            $DB->exec("INSERT INTO tblbuddies (name, email, photo)
                                    VALUES ('$name','$email','$photo')");
                            echo "<span style='background-color:yellow'>";                
                            echo "Data added successfully";            
                            echo "</span>";                
                            // close the database connection
                            $DB = NULL;
                        }        
                                catch(PDOException $e){
                            echo 'Exception : '.$e->getMessage();
                        }
}
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>E-mail: <input type="email" name="email"
        required placeholder="Enter a valid email address"></p>
<p>Photo: <input type="hidden" name="photo">
<input type="file" onchange="previewFile()">
<p><img src="" height="100" alt="Image preview..."></p>
<p><input type="submit" value='Submit' name="submit"></p>
</form>
<script>
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
   reader.addEventListener("load", function () {
     preview.src = reader.result;
    var file = document.querySelector('input[type=file]').files[0];
    document.getElementsByName("photo")[0].value = preview.src;    
   }, false);
  if (file) {
    reader.readAsDataURL(file);
  }
}
</script>
</body>
</html>
This produces the same outcome as before but with a new blank form for user to enter the next record.
This is useful particularly when the user expects to enter records one after another.
.

1 comment:

Labels