Table of Contents

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

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 Alias:</label>
                        <input type="text" name="alias" size="30" maxlength="50" hint="Iron Man">
                    </li>
                    <li>
                        <label>Hero Name:</label>
                        <input type="text" name="identity" size="30" maxlength="50" hint="Tony Stark">
                    </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['alias']; ?>"><?php echo $row['alias']; ?></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

aliasidentityhero_villainfirst_appearedpower
ThorThor Odinson1962Magic
Red SkullJohan Schmidt1941Biological
Winter SolBucky BarnesWinter Soldier1941Tech
Clint BartonHawkeye1969Skill
OdinOdin1962Magic
Nick FuryNick Fury1963Skill
Phil CoulsonAgent Coulson2008Skill
Peter QuillStarlord1976Tech
GamoraGamora1975
Pepper PottsRescue1963Tech
INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES ('Bucky Barnes', 'Winter Soldier', 'Villain', '1941', 'Tech'); 

Switch Statement

    // check which form
    if ($_POST['submit'] == 'Add Hero') {

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

    } else {
        
    }
    switch ($variable) {
        case 'value':
            # code...
            break;
        
        default:
            # code...
            break;
    }
switch ($age) {
    case 1:
    case 17:
    case 43:
        # code...
        break;
    case 22:
    case 39:
        # code...
        break;
}
    switch ($_POST['submit']) {
        case 'Add Hero':
            break;
        case 'Add Appearance':
            break;
        default:
            break;
    }
            $query = "";
            $args  = array();
            $rslt  = $pdo->prepare($query);
            $rslt->execute($args)
            $query = "INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)";
            $args  = array($_POST['alias'], $_POST['identity'], $_POST['alias'], $_POST['side'], $_POST['year'], $_POST['power']);
            if ($rslt->execute($args)) {

            } else {
            
            }
            if ($rslt->execute($args)) {
                $message = "{$_POST['name']} was inserted successfully.";
            } else {
                $message = "There was a problem inserting {$_POST['name']}.";
            }

Multiple Inserts

INSERT INTO appearances (character_name, movie) VALUES ('Thor Odinson', 'Thor: Dark World'), ('Thor Odinson', 'Avengers: Age of Ultron')

Array Push

            foreach($_POST['movie'] as $movie) {

            }
                        array_push($args, $_POST['hero'], $movie);
            $args = array();
            foreach($_POST['movie'] as $movie) {
                        array_push($args, $_POST['hero'], $movie);
            }
                    // check if it exists already
                    $mquery = "SELECT * FROM appearances WHERE character_name=? AND movie=?";
                    $margs  = array($_POST['hero'], $movie);
                    $rslt  = $pdo->prepare($mquery);
                    $rslt->execute($margs);
                    if (!$row = $rslt->fetch()) {
                        array_push($args, $_POST['hero'], $movie);
                    }
                if ($movie == 'new') {
                    array_push($args, $_POST['hero'], $_POST['new_movie']);
                } else {
                    // check if it exists already
                    $mquery = "SELECT * FROM appearances WHERE character_name=? AND movie=?";
                    $margs  = array($_POST['hero'], $movie);
                    $rslt  = $pdo->prepare($mquery);
                    if (!$rslt->execute($margs)) {
                        array_push($args, $_POST['hero'], $movie);
                    }
                }

Count

            $movies = count($args)/2;

Repeating String

            $values = str_repeat('(?,?), ', $movies-1) . '(?,?)';
            $query = "INSERT INTO heroes ('alias', 'movie') VALUES $values";
            error_log("MURRAY: $query\n" . print_r($args, 1);
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "$movies appearances were inserted successfully.";
                } else {
                    $message = "There was a problem inserting $movies appearances.";
                }
            if ($movies > 0) {
                $values = str_repeat('(?,?), ', $movies-1) . '(?,?)';
                $query = "INSERT INTO appearances (alias, movie) VALUES $values";
                error_log("MURRAY: $query    " . print_r($args, 1));
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "$movies appearances were inserted successfully.";
                } else {
                    $message = "There was a problem inserting $movies appearances.";
                }
            } else {
                $checked = count($_POST['movie']);
                $message = "All $checked appearances are already in the database.";
            }

Next: UPDATE Queries