User Tools

Site Tools


en:web_development:forms:insert

This is an old revision of the document!


Web Development Lesson 8 - Forms

Insert Queries

Objective

In this activity you'll learn how to obtain data from a form and insert it into a database table.

Setup

  • We'll continue using 'form.php' and 'process_form.php'. If you need the code again, here it is.

form.php

<?php
    include('database.php');

    include('header.php');
    include('menu.php');

    // get list of heroes
    $query = "SELECT * FROM heroes";
    $args  = array();
    $hrslt = $pdo->prepare($query);
    $hrslt->execute($args);

    // get list of movies
    $query = "SELECT movie FROM appearances GROUP BY movie";
    $args  = array();
    $mrslt = $pdo->prepare($query);
    $mrslt->execute($args);
?>
    <main>
        <form name="add_hero" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Hero</legend>
                <ul>
                    <li>
                        <label>Hero Name:</label>
                        <input type="text" name="name" size="30" maxlength="50">
                    </li>
                    <li>
                        <label>Side:</label>
                        <ul>
                            <li><input type="radio" name="side" value="Hero" checked> Hero</li>
                            <li><input type="radio" name="side" value="Villain"> Villain</li>
                        </ul>
                    </li>
                    <li>
                        <label>First Appearance:</label>
                        <input type="number" name="year">
                    </li>
                    <li>
                        <label>Source of Power:</label>
                        <select name="power">
                            <option value="skill">Skill</option>
                            <option value="bio">Biological</option>
                            <option value="magic">Magic</option>
                            <option value="tech">Technology</option>
                            <option value="mutant">Mutant</option>
                        </select>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add Hero">
            </fieldset>
        </form>

        <form name="add_appearances" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Appearances</legend>
                <ul>
                    <li>
                        <label>Hero</label>
                        <select name="hero">
<?php
    // display list of heroes
    while($row = $hrslt->fetch()) {
?>
                            <option value="<?php echo $row['character_name']; ?>"><?php echo $row['character_name']; ?></option>
<?php
    }
?>
                        </select>
                    </li>
                    <li>
                        <label>Movie</label>
                        <ul>
<?php
    // display list of movies
    while($row = $mrslt->fetch()) {
?>
                            <li><input type="checkbox" name="movie[]" value="<?php echo $row['movie']; ?>" id=""> <?php echo $row['movie']; ?></li>
<?php
    }
?>
                            <li><input type="checkbox" name="movie[]" value="new" id=""> <input type="text" name="new_movie"></li>
                        </ul>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add Appearance">
            </fieldset>
        </form>
    </main>
<?php
    include('footer.php');
?>

process_form.php

<?php
    include('header.php');
    include('menu.php');
?>
    <main>
        <p><?php print_r($_POST); ?></p>
    </main>
<?php
    include('footer.php');
?>

INSERT Query

  • To see how this works, we'll start in PHPMyAdmin.
  • Log in and open the table 'heroes' in the database 'webdev'.
  • Open the 'Insert' tab.
  • Notice that each of the fields in our table is represented by a row.
  • Pick a hero / villain from the following list and add it to the table. If you're working in a class, each pick a different character.
character_namealiashero_villainfirst_appearedpower
ThorThor1962Magic
Johan SchmidtRed Skull1941Biological
Bucky BarnesWinter Soldier1941Tech
Clint BartonHawkeye1969Skill
OdinOdin1962Magic
Nick FuryNick Fury1963Skill
Phil CoulsonAgent Coulson2008Skill
Peter QuillStarlord1976Tech
GamoraGamora1975
Pepper PottsRescue1963Tech
  • Enter the information for your hero into the appropriate fields in the 'Value' column and press 'Go'.
  • See the query used to add the data just below the yellow row at the top of the page.
INSERT INTO `heroes` (`character_name`, `alias`, `hero_villain`, `first_appeared`, `power`) VALUES ('Bucky Barnes', 'Winter Soldier', 'Villain', '1941', 'Tech'); 
  • This is the format we need to use for our insert query in 'process_form.php'.
  • An INSERT query always begins with 'INSERT INTO' and the name of the table we will use, then a list of the fields we want to add to.
  • This is followed by 'VALUES' and a list of the values to be inserted.

Switch Statement

  • Remember that we actually have two forms sent to this page by two submit buttons.
  • We can identify which form to process by the value of '$_POST['submit']'.
  • We could do this with an 'if' statement, like this.
    // check which form
    if ($_POST['submit'] == 'Add Hero') {

    } else if ($_POST['submit'] == 'Add Appearance') {

    } else {
        
    }
  • This would work, but there is a better way.
  • A 'switch statement' isn't as flexible as an 'if statement', which allows for completely new conditions on each line, but it is more powerful in its own way.
  • Open 'process_form.php' in Visual Studio Code.
  • At the end of the first PHP block, type 'switch' and select the second option. It will add the following code automatically.
    switch ($variable) {
        case 'value':
            # code...
            break;
        
        default:
            # code...
            break;
    }
  • This statement checks the value of '$variable' and looks down the list of 'cases' until it finds a match, then runs the code until it hits a break command.
  • If it doesn't find a match, then it runs the code in default:.
  • This means that if don't include break at the end of a case, the code from the next case will also run. This can be useful if you want the same code to run for multiple cases like this. (Don't add this code)
switch ($age) {
    case 1:
    case 17:
    case 43:
        # code...
        break;
    case 22:
    case 39:
        # code...
        break;
}
  • We want to run a different query depending on the value of $_POST['submit'], so replace '$variable' with $_POST['submit'].
  • Now set up a case each for 'Add Hero' and 'Add Appearance'.
    switch ($_POST['submit']) {
        case 'Add Hero':
            break;
        case 'Add Appearance':
            break;
        default:
            break;
    }
  • Insert our code that we use for running database queries after case 'Add Hero':.
            $query = "";
            $args  = array();
            $rslt  = $pdo->prepare($query);
            $rslt->execute($args)
  • We can now copy our query from PHPMyAdmin to the query string.
  • Because hackers can perform 'SQL Injection' to get information about your database or even to add themselves as an admin user by adding SQL code as data, we're going to strip the data out of our query.
  • Replace each value with ? then add the respective user input as elements in the '$args' array.
            $query = "INSERT INTO `heroes` (`character_name`, `alias`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)";
            $args  = array($_POST['name'], $_POST['alias'], $_POST['side'], $_POST['year'], $_POST['power']);
  • This code will work unless there is a problem accessing the database or invalid user input.
  • Since we want to know if there's a problem, and to tell the user, let's add a check.
  • Change $rslt->execute($args) to the following.
            if ($rslt->execute($args)) {

            }
  • Add a message in this code block.
            if ($rslt->execute($args)) {
                $message = "{$_POST['name']} was inserted successfully.";
            }

Multiple Inserts

  • The Add Appearances form allows the user to add multiple movies, but each one is its own line in the database table.
  • We could create a separate query for each movie, but its also possible to add multiple lines in the same query.
  • First we need to check how many movies have been added.
en/web_development/forms/insert.1642698225.txt.gz · Last modified: 2023/08/16 09:33 (external edit)