Noob Question Form submitted PHP to mysql

Hi folks can 't for the life of me figure why this doesn’t work - I have a form in html:

[php]

    <label for="comment_1">Comment to Add:</label>
    <input type="text" name="comment_1" id="comment_1">


<input type="submit" value="Submit">
[/php]

Then this PHP to handle the submission:

[php]
if(isset($_post[‘comment_1’]))
{
$addedcomm = $mysqli_real_escape_string($link, $_POST[‘comment_1’]);

$sql = “INSERT INTO comments (comment) VALUES (’$addedcomm’)”;

header(‘Location: .’);
exit();
}[/php]

I’m sure it’s a daft error somewhere, but the form submits but doesn’t update the DB

There’s plenty of errors in both the HTML and PHP. However, the first thing to do is turn on error reporting.

Put this on top of your page:
[php]error_reporting(E_ALL);
ini_set(‘display_errors’, 1);[/php]

[php]
Comment to Add:

[/php]

Fixes up the form a bit, but just looking over the HTML I would suggest having better knowledge of HTML would help you out a lot. You should be using instead of type=“text”.

Here’s a example take from my contact page:
[php]

{$success}

Name

            <label for="email" accesskey="E">Email</label>
            <input name="email" type="email" id="email" tabindex="2" required="required" />

            <label for="phone" accesskey="P" >Phone <small>(optional)</small></label>
            <input name="phone" type="tel" id="phone" tabindex="3">

            <label for="web" accesskey="W">Website <small>(optional)</small></label>
            <input name="website" type="text"  id="web" tabindex="4">

            <div class="radioBlock">
                <input type="radio" id="radio1" name="reason" value="message" tabindex="5" checked>
                <label class="radioStyle" for="radio1">message</label>
                <input type="radio" id="radio2" name="reason" value="order">
                <label class="radioStyle" for="radio2">order</label>  
                <input type="radio" id="radio3" name="reason" value="status">
                <label class="radioStyle" for="radio3">status inquiry</label>    
            </div>

            <label class="textBox" for="comments">Comments</label>
            <textarea name="comments" id="comments" spellcheck="true" tabindex="6" required="required"></textarea> 
            <div class="g-recaptcha" data-sitekey="6LfPlQoUAAAAAPgD3PpnQ_uGTzc87UALiFgQ3XnK"></div>
            <input type="submit" name="submit" value="submit" tabindex="7">
        </fieldset>
    </form>[/php]

Ignore the curly brackets {} for I’m using Smarty (a templating language} though the over form should give you a good idea.

cheers - I know the HTML is a mess, atm just trying to understand why the value isn’t being added to the SQL db

Your form processing code isn’t being executed because if(isset($_post[‘comment_1’])) needs to be if(isset($_POST[‘comment_1’])). Php variables are case sensitive.

If that’s all the form processing code, it’s not executing the query, nor is it making a database connection.

Also, the various …_escape_string() functions are subject to sql special characters in the data breaking the sql query syntax (which is how sql injection is accomplished) if the character encoding being used by php doesn’t match the character encoding being used by your database. A fool-proof way of preventing problems is to use prepared queries, with place-holders in the sql query statement for data, then supply the actual data when the query is executed. You can research in the php.net documentation or on the web to find out about prepared queries. Unfortunately, the php mysqli extension is not very well designed, especially concerning prepared queries. If you can, switch to the much simpler and better designed php PDO extension.

cheers phdr = th efull code is here (changed comment tag) i know i’m missing a lot of error checks etc - there’s an output page so there’s def a connection:

[php]<?php
$link=mysqli_connect(“localhost”,“root”,“01222531063”,“commdb”); //connecting

if (isset($_GET[‘addcomment’]))
{
include ‘inputform.html.php’;
exit();
}
// Check connection
if (!$link)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($link, ‘SELECT comment FROM comments’);
if (!$result)
{
$error = 'Error fetching comments: ’ . mysqli_error($link);
include ‘error.html.php’;
exit();
}
while ($row = mysqli_fetch_array($result))
{
$comments[] = $row[‘comment’];
}

if(isset($_POST[‘comment1’]))
{
$addedcomm = $mysqli_real_escape_string($link, $_POST[‘comment1’]);

$sql = “INSERT INTO comments (comment) VALUES (’$addedcomm’)”;

header(‘Location: .’);
exit();
}

include ‘commentpage.html.php’;

?>[/php]

I always wanted to create a tutorial on how to insert data to a database table, so here it is.

First you want to create a basic configuration file of some sort.

Here’s the one I created called config.php and it is located in the same directory as the other files.
[php]<?php

error_reporting(E_ALL);
ini_set(‘display_errors’, 1);
define(‘DATABASE_HOST’, ‘local_host_name’);
define(‘DATABASE_NAME’, ‘myCMS’);
define(‘DATABASE_USERNAME’, ‘username’);
define(‘DATABASE_PASSWORD’, ‘password’);
define(‘DATABASE_TABLE’, ‘myBlog’);
[/php]

Here’s an file called install.php that creates the database and database table:
[php]<?php
require_once ‘config.php’; // Configuration file for turning error reporting and connection strings to database:

/*

  • I think the following is pretty self explanatory and I think think the index.php file helps you on how to insert
  • data into a database table better.
    */
    try {
    $conn = new PDO(‘mysql:host=’ . DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = “CREATE DATABASE IF NOT EXISTS myCMS”;
    $conn->exec($sql);
    $sql = “use myCMS”;
    $conn->exec($sql);
    $sql = “CREATE TABLE IF NOT EXISTS myBlog (
    ID int(11) AUTO_INCREMENT PRIMARY KEY,
    title varchar(30) NOT NULL,
    comment text NOT NULL)”;
    $conn->exec($sql);
    echo “DB created successfully”;
    } catch (PDOException $e) {
    echo $sql . “
    ” . $e->getMessage();
    }[/php]

And lastly the file (index.php) to insert user’s data from a HTML Form into a database table called myBlog.
[php]<?php
require_once ‘config.php’; // Configuration file for turning error reporting and connection strings to database:

/*

  • The first thing to do is to make sure you have a database named myCMS and a database table named myBlog.
  • You can run the install file that will create the database and database table by running install.php if you want
  • or you can create the database and database table yourself.
    */

/*

  • Establish a database connection.
    /
    $db_options = [
    /
    important! use actual prepared statements (default: emulate prepared statements) /
    PDO::ATTR_EMULATE_PREPARES => false
    /
    throw exceptions on errors (default: stay silent) /
    , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    /
    fetch associative arrays (default: mixed arrays) */
    , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ];
    $pdo = new PDO(‘mysql:host=’ . DATABASE_HOST . ‘;dbname=’ . DATABASE_NAME . ‘;charset=utf8’, DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);

/*

  • Check to see if user has clicked on the submit button.
    */
    $submit = filter_input(INPUT_POST, ‘submit’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if (isset($submit) && $submit === “submit”) {
/*
* Grab User’s Responses from Form.
/
$title = htmlspecialchars($_POST[‘title’]);
$comment = htmlspecialchars($_POST[‘comment’]);
/

* Insert Into Database Table myBlog.
*/
$query = ‘INSERT INTO myBlog(title, comment) VALUES (:title, :comment)’;
$stmt = $pdo->prepare($query);
$result = $stmt->execute([’:title’ => $title, ‘:comment’ => $comment]);

if ($result) {
    header("Location: index.php");
    exit();
}

}
?>

PHP Comment Tutorial * { box-sizing: border-box; } body { background-color: #ccc; padding: 0; margin: 0; } form#commentForm { display: block; width: 100%; max-width: 400px; height: auto; background-color: #fff; padding: 15px; margin: 20px auto; } form#commentForm fieldset { border: 1px solid #336699;} form#commentForm legend { font-family: Arial, Helvetica, sans-serif; font-size: 1.2em; color: #336699; padding: 0 5px; } form#commentForm label { float: left; display: block; width: 100%; max-width: 140px; height: 30px; font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; line-height: 30px; color: #336699; text-align: left; padding: 0; } form#commentForm input { clear: right; display: block; width: 100%; max-width: 280px; height: 30px; border: 1px solid #336699; outline: none; font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; color: #2e2e2e; padding: 0 5px; margin-bottom: 10px; } form#commentForm label.textBox { clear: both; text-align: left; font-size: 1.2em; padding: 0; margin-top: 20px; } form#commentForm textarea { resize: none; border: 1px solid #336699; outline: none; clear: both; display: block; width: 100%; max-width: 360px; height: 300px; font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; line-height: 1.5; color: #2e2e2e; padding: 10px; } form#commentForm input[type=submit] { -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; -moz-box-shadow: 2px 2px 3px rgba(46, 46, 46, 0.4); -webkit-box-shadow: 2px 2px 3px rgba(46, 46, 46, 0.4); box-shadow: 2px 2px 3px rgba(46, 46, 46, 0.4); outline: none; border: none; float: right; display: block; width: 100%; max-width: 120px; height: 40px; cursor: pointer; background-color: #4484CE; font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; color: #fff; text-transform: capitalize; margin-top: 20px; } form#commentForm input[type=submit]:hover { background-color: #2e2e2e; color: #ffa; } Comment Form Title Comment [/php]

It’s a very simple tutorial, it’s not flashy, and it probably could had been coded different way. Though every coder programs differently, but that is what makes programming fun and interesting. :wink: This should give anyone a basic start on how to get started with interacting with MySQL with PHP and I plan on writing tutorials on reading data from a table, updating and deleting from a table in the near future.

Hope this Helps ~ John

I have updated my tutorial and decided to post it to a Github repository: https://github.com/Strider64/PHP_PDO_Tutorial

This
[php] $submit = filter_input(INPUT_POST, ‘submit’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if (isset($submit) && $submit === “submit”) {[/php]

Should be replaced with

[php]if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {[/php]

Depending on the name of a button to be submitted for your application to work will completely fail in certain circumstances. It will also become problematic when your application has multiple language options.

Sponsor our Newsletter | Privacy Policy | Terms of Service