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
Thor OdinsonThorHero1962Magic
Johan SchmidtRed SkullVillain1941Biological
Bucky BarnesWinter SoldierVillain1941Tech
Clint BartonHawkeyeHero1969Skill
OdinOdinHero1962Magic
Nick FuryNick FuryHero1963Skill
Phil CoulsonAgent CoulsonHero2008Skill
Peter QuillStarlordHero1976Tech
GamoraGamoraHero1975
Pepper PottsRescueHero1963Tech
  • Enter the data for the chosen character and click 'Go' to submit.
  • Notice at the top of the screen just below the yellow bar it shows the query used to add the data.
  • It will look something like this.
INSERT INTO `heroes` (`character_name`, `alias`, `hero_villain`, `first_appeared`, `power`) VALUES ('Thor', 'Thor', 'Hero', '1962', 'Magic'); 
  • This is the query format we need to use in our page to add new information.
  • It starts with INSERT INTO then the name of the table.
  • Next, inside () we add the list of fields that we have data for.
  • Then VALUES () with the data inside the () .
  • Actually, we'll change this a little. Hackers will sometimes use SQL Injection to get information from, or change information in, your database. To avoid this, we replace the data with ? and put the actual values in an array to be sent separate to the query.
  • The query then looks like this.
INSERT INTO `heroes` (`character_name`, `alias`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)
  • With an arguments array like this.
('Thor', 'Thor', 'Hero', 1962, 'Magic')

Switch Statement

  • Return to Visual Studio Code.
  • Open 'process_form.php' and switch it to PHP mode (bottom right corner).
  • First we must determine which form to process. We can tell by checking the value of $_POST['submit'], which will be either 'Add Hero' or 'Add Appearance' depending on which form has been submitted.
  • You know how to check each one using if , but there's another more powerful option you can use when you are checking for different values of the same variable.
  • At the end of the first PHP block, type switch and select 'switch block' (the second option).
  • You'll see this.
    // check which form
    switch ($variable) {
        case 'value':
            # code...
            break;
        
        default:
            # code...
            break;
    }
  • switch allows us to check the value of a particular variable (in this case $_POST['submit']) and run different code based on the result.
  • The expected results are listed in separate case values.
  • default: will run if the result is something unexpected / undefined.
  • Also note break; at the end of each case code block. If you leave this out, the code in the next case will keep running until eventually it hits break; or the end of the switch statement. This can be useful if you want the same code to be run in multiple options.
  • Replace '$variable' with '$_POST['submit']'.
  • Replace 'value' with 'Add Hero'.
  • Add another case block for 'Add Appearance'.
  • Delete '# code…' from each block.
  • The code should look like this so far.
    // check which form
    switch ($_POST['submit']) {
        case 'Add Hero':
            break;
        case 'Add Hero':
            break;
        default:
            break;
    }

PDO Query

  • Let's start with the code to add a hero. Add a new line after case 'Add Hero':.
  • Add the query and arguments.
            $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']);
  • Now add the code to execute our query.
            $rslt = $pdo->prepare($query);
            $rslt->execute($args);
  • Because we want to know whether it worked, let's update the last line to return a status message.
            if ($rslt->execute($args)) {
                $message = "{$_POST['name']} was inserted successfully.";
            }
  • Note that $_POST['name'] is wrapped in {} . This is to tell PHP that we want the value printed, not the text as is. Try removing {} to see what the message says without them.
  • Then we can display the message in <main>.
    <main>
        <p><?php echo $message; ?></p>
    </main>

New Movie

en/web_development/forms/insert.1642632121.txt.gz · Last modified: 2023/08/16 09:33 (external edit)