php – Inserting and Displaying Information From a Database

This is a very simple example of inserting an entry in a mysql database, using PHP. This script will also show a simple example of listing the entries in your field.

Here is the script “flow-chart” for your viewing pleasure:

-intitialize some variables
-connect to the database
-insert a new row into the database (conditional)
-select info from the database
-print info to the screen
-print out a form to add new entries

First off, you will want to create a table and a field. Here is a sample query for you to insert into phpmyadmin or your command line prompt or whatever:

PHP Example:
// Mysql Query
CREATE TABLE `testTable` (
`someField` VARCHAR( 20 ) NOT NULL

Now that you have your table and field and know the battle plan, here is the complete script, and then we’ll break it down piece by piece:

PHP Example:
// Php Code

// database information
$host = ‘localhost’;
$user = ‘username’;
$password = ‘password’;
$dbName = ‘databasename’;

// connect and select the database
$conn = mysql_connect($host, $user, $password) or die(mysql_error());
$db = mysql_select_db($dbName, $conn) or die(mysql_error());

// insert new entry in the database if entry submitted
if (isset($_POST[‘newEntry’]) && trim($_POST[‘newEntry’]) != ”) {
// for easier variable handling…
$newEntry = $_POST[‘newEntry’];

// insert new entry into database
$sql = “insert into testTable (someField) values (‘$newEntry’)”;
$result = mysql_query($sql, $conn) or die(mysql_error());
} // end if new entry posted

// select all the entries from the table
$sql = “select someField from testTable”;
$result = mysql_query($sql, $conn) or die(mysql_error());

// echo out the results to the screen
while ($list = mysql_fetch_array($result)) {
echo “{$list[‘someField’]} <br>”;
} // end while

// echo out the form to add a new entry
echo <<<FORMENT
<br> Make a new entry: <br>
<form action = “{$_SERVER[‘PHP_SELF’]}” method = “post”>
<input type = “text” name = “newEntry” maxlength=”20″ size = “10”>
<input type = “submit” value = “Add Entry”>


  1. siva said


  2. amitmondal said

    Nice tutorial….thanks for this post…..
    Please visit this link for learn more script.

  3. frenky said


RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: