
Oct 21st, 2007, 10:47
|
 |
SuperMember
|
|
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
|
Stick it In -- Inserting data via SQL with PHP
This is part one inserting data from a form into the database with a fair amount of data checking.
- PHP: Select all
<?php
// Okay, so we're only going to worry about adding anything to the database if the user has actually submitted the form
// We do this by checking of the submit button has been passed to the server we will check all data sent using
// $_POST becuase the action of out form is method="post" if it was method="get" we would replace $_POST with $_GET
// The name of our submit buttin is 'submitPig' so e check for that
if (isset($_POST['submitPig'])) // Isset checks that the variable has been set (does not check value its any usable type.. eg could be NULL or false)
{
// Let's connect to the database
$con = mysql_connect('localhost', 'root', 'guineapigsrule')
or
// By adding the or die line we make it so the script will not continue if we cannot connect.
die ('Oh no! We could not connect');
// now select the database to be used
mysql_select_db('guineapigs', $con) // databasename and then the connection id from above
or
die (mysql_error()); // die with mysql error response if we cannot select the database.
// for the purpose of this script, we will assume that all form fields are *required*
// this means that if there is something missing after our simple validation, we will
// not add anything to the database
$errors = array(); // initialise an error array
// The validation in use is very simple, it would be recommended to check in more detail in a live script
// Check for a guineapig name
$_POST['pigName'] = @trim($_POST['pigName']); // trim the whitespace from both ends
if (empty($_POST['pigName']) || !ctype_alpha($_POST['pigName']) || strlen($_POST['pigName']) > 50)
// empty checks to be sure that the field is 1)not set or 2) has a value other than '', false, 0 or NULL
// !ctype_aplha checks to make sure that the field only has alphabetic letters
// strlen to check that field is not too long
$errors[] = 'Your guinea pig must have a name that is only letters and is less than 50 characters';
else
// Everything checks out so we will escape the data ready to insert into the database
$_POST['pigName'] = mysql_real_escape_string($_POST['pigName']);
// Now check the rest of the fields
$_POST['pigColour'] = @trim($_POST['pigColour']);
if (empty($_POST['pigColour']) || !ctype_alpha($_POST['pigColour']) || strlen($_POST['pigName']) > 20)
$errors[] = 'Your piggie has no colour or has more than 20 letters or some crazy character in it. Please fix';
else
$_POST['pigColour'] = mysql_real_escape_string($_POST['pigColour']);
$_POST['pigAge'] = @trim($_POST['pigAge']);
if (empty($_POST['pigAge']) || !is_numeric($_POST['pigAge']) || $_POST['pigAge'] > 999)
// Different check for a number, check that it is a number with !is_numeric and check that it is less that max 999
$errors[] = 'And *how* old is your little piggie? Make sure it\'s just numbers and less than 999.';
else
$_POST['pigAge'] = mysql_real_escape_string($_POST['pigAge']);
// Now check the rest of the fields
$_POST['pigDescription'] = @trim($_POST['pigDescription']);
if (empty($_POST['pigDescription']))
$errors[] = 'Can you please tell us a little bit about your piggie? I would love to know. Phanks summuch';
else
$_POST['pigDescription'] = mysql_real_escape_string($_POST['pigDescription']);
// Now we have checked all of the fields, one of two this has happened
// 1 -- we have allrequired data (BONZA!!)
// 2 -- We don't
// We will not continue if we have any errors
$ne = count($errors); // Count the errors
if (!$ne) { // If there are no errors we will go to the database entry
// Okay, when we are inserting a new record into the database the format for the SQL is
// INSERT INTO tablename (column1, column2, column3)
// VALUES (value1, value2, value3)
// In our example the query will look something like this if we wrote it from scratch
// INSERT INTO petGuineapigs (pigName, pigColour, pigAge, pigDescription)
// VALUES ('Johnny', 'BabyPooBrown', 67, 'Johnny is a hyperactive scamp, always running around')
// Some things to note, you need to surround non-number values with quotes and you need to specify the values in
// the order you lay out the columns. If you have a column with AUTO_INCREMENT you *do not* specify this value
// It will increase by itself
// Now to contruct our query
// When we are inserting values into a string from an array surround them in {curly braces} so PHP knows they
// have special meaning
$query = "INSERT INTO petGuineaPigs (pigName, pigColour, pigAge, pigDescription)
VALUES ('{$_POST['pigName']}', '{$_POST['pigColour']}', {$_POST['pigAge']}, '{$_POST['pigDescription']}')";
// now we will run the query
mysql_query($query)
or
die ('OH NO! All that work for nuffin ' . mysql_error());
// Because we didn't die, we can call it a success. Becuase mySQL will increment the primary id for us we can
// can retrieve it
$insertedID = mysql_insert_id();
// Get the message to give to the user
$message = 'Hooray, we saved your guinea pig! It\'s unique id id ' . $insertedID;
} else {
// Now we are in here because we had some errors so we will add the errors to a message string
// to display later.
$message = '<strong>Something went awry!</strong>
<ol>';
foreach ($errors as $error)
$message .= '<li>' . $error . '</li>';
$message .= '</ol>';
}
}
?>
<html>
<head>
<!-- Head stuff here //-->
</head>
<body>
<?php
// Echo the message from above it is set
echo !empty($message) ? $message : '';
?>
<!-- The form goes below etc.... //-->
</body>
</html>
Last edited by Rakuli; Oct 28th, 2007 at 09:53.
Reason: Attached file for easier viewing
|