Blog

Sample PHP and MySQL to Insert Data from a Field Field into a MySQL Database and Display It on Another Page
Posted on June 19, 2015 in MySQL, PHP by Matt Jennings

Code on process.php which Process a Form on Another Page

    /*
    Set 'name' and 'quote' input/text area session variables
    if they don't exist
    */
    if(!isset($_SESSION['name']) && !isset($_SESSION['quote']))
    {

        $_SESSION['name'] = $_POST['name'];
        $_SESSION['quote'] = $_POST['quote'];

        // Save a MySQL query as a $query variable using
        // data from form fields
        $insert_query = "INSERT INTO quotes(name, quote, created_at, updated_at) VALUES ('{$_SESSION['name']}', '{$_SESSION['quote']}', NOW(), NOW())";

        // Pass the $query variable into a called function
        // and save it as a $execute_query variable
        $execute_insert_query = run_mysql_query($insert_query);

        header('Location: main.php');

    }

Code on main.php, a Page we Redirected to Per the PHP Above, that Displays the Inserted MySQL Data

<?php
session_start();
require_once('includes/new-connection.php');

// Code need to select and display
// data from the MySQL table
$quotes_table_query = "SELECT * FROM quotes";
$quotes = fetch($quotes_table_query);


/*
PHP and HTML Here
*/


// Display MySQL data inserted into the MySQL DB
// from a form on another page
foreach(array_reverse($quotes) as $quote)
{
    echo '<p><span class="big">&ldquo;</span>' . $quote['quote'] . '<span class="big">&rdquo;</span><br /><span class="float-right">' . $quote['name'] .'</span></p>';
}
?>

Leave a Reply

To Top ↑