View Full Version : PHP - detection of field names
imagined
September 11th, 2007, 11:12 AM
Im programming a Content Management System and there is a lot of different forms and fields that users have to fill out and the information submitted is entered into a MySQL database.
Is there a way to create a function that will scan the file, find out the field names, validate the form (like make sure phone numbers are digits and make sure email address was properly entered) and create a database query according to the field names?
That way, I would only have ONE function to input the information in MOST of my forms and save a lot of repetitive work.
I know lots of us will find a function like this useful. Im going to do a search for something like this and I will post what I find. If I dont find anything and there is no one that as a function like this, I will try to create a function like this. But if you already have it please share it.
Thanks,
Leo
DHDesign
September 11th, 2007, 12:27 PM
im not sure if this is what you are looking for...but i got this code from another site (i would love to give them credit but cant remember the site name or URL)...anyway:
function AddToDB($tbl)
{
$conn = db_connect();
// Set the arrays we'll need
$sql_columns = array();
$sql_columns_use = array();
$sql_value_use = array();
// Pull the column names from the table $tbl
$pull_cols = mysql_query("SHOW COLUMNS FROM ".$tbl) or die("MYSQL ERROR: ".mysql_error());
// Pull an associative array of the column names and put them into a
// non-associative array
while ($columns = mysql_fetch_assoc($pull_cols)){
$sql_columns[] = $columns["Field"];
}
foreach( $_POST as $key => $value )
{
// Check to see if the variables match up with the column names
if ( in_array($key, $sql_columns) && trim($value) )
{
//THIS AREA CAN BE USED FOR CALLING VALIDATION FUNCTIONS...HERE ARE TWO EXAMPLES
//change date to MySQL format if form field name has Date in it
if(testforword($key,"Date")){
if($value!=""){
$value = format_date($value);
}
}
//if a new password is being supplied, md5 it first before inputting into DB
if(testforword($key,"AdminPass")){
if($value!=""){
$value = md5($value);
}
}
// If this variable contains a number, then don't add single
// quotes, otherwise check to see if magic quotes are on and use
// addslashes if they aren't
if ( is_numeric($value) ) {
$sql_value_use[] = $value;
} else {
$sql_value_use[] = ( get_magic_quotes_gpc() ) ?
"'".$value."'" : "'" .addslashes($value)."'";
}
// Put the column name into the array
$sql_columns_use[] = $key;
}
}
// If $sql_columns_use or $sql_value_use are empty then that means no values matched
if ( (sizeof($sql_columns_use) == 0) || (sizeof($sql_value_use) == 0) )
{
// Set $Error if no values matched
print "Error: No values were passed that matched any columns.";
return false;
} else {
// Implode $sql_columns_use and $sql_value_use into an SQL insert sqlstatement
$SQLStatement = "INSERT INTO ".$tbl." (".implode(",",$sql_columns_use).") VALUES (".implode(",",$sql_value_use).")";
// Execute the newly created statement
if ( @mysql_query($SQLStatement) ){
while(list($filename, $filevalue) = each($_FILES))
{
//check to see if an attachment was included or not
if(!empty($_FILES[$filename]['tmp_name'])){
$last_insert_id = mysql_insert_id();
if(move_uploaded_file($_FILES[$filename]['tmp_name'], "attachments/$last_insert_id"."_".$_FILES[$filename]['name'])){
$table_columns = array();
$table_columns = table_to_array($tbl); //custom function that I built
$filelocation = "attachments/$last_insert_id"."_".$_FILES[$filename]['name'];
$SQLFileUpload = "UPDATE $tbl SET FileLocation='$filelocation' WHERE Item_ID='$last_insert_id'";
$ProcessUpdate = mysql_query($SQLFileUpload);
} else {
print "Error uploading file. Please contact Application Administrator.";
}
}
}
return true;
} else {
// Set $Error if the execution of the statement fails
print "Error: ".mysql_error();
return false;
}
}
}
the testforword function that is called in the above for the individual form element validations or other actions to be taken:
function testforword ($checkinput, $word){
// Check if variable string has the word $word in it
$textarray=explode("_",$checkinput);
$numberofwords=count($textarray);
for($x=0;$x<=$numberofwords;$x++){
if($textarray[$x]==$word){
return TRUE;
}
}
return FALSE;
}
hope this helps...let me know if you want explanations, but its pretty self-explanatory...takes $_POSTS, matches to table column names, does some validation, inputs into table, has an optional file check to see if files are being uploaded and then upload to certain directory and place into a table as well for file location.
not sure if this is what you meant, but anyway, id thought id post this.
cheers.
simplistik
September 11th, 2007, 12:57 PM
It's easily possible to do it if you just run a standard $_POST, it'll drop all your names into an array, if each name is consistent you can include in your function things like
function fieldCheck()
{
if ( $_POST['phone'] )
{
// do something like strip anything that's not 0-9, check str length, etc.
}
}
We do similar automated stuff in my company, but I'm not at liberty to share it cause a) it's quite complex, b) it's unique to our company, c) if everyone else had it then we wouldn't have an "upper hand" :D
imagined
September 11th, 2007, 05:37 PM
Thanks guys!
Your replies have helped me come up with a simple function. Now I need to create some kind of validation. Like if the field name is something like "phone" or "zipcode" to check that the user only entered numbers; and if the field name contains the word "email" to check if the email was properly entered.
I already have some code that will help me achieve this. If you have any other suggestions please let me know. Here is a sample of how it could work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<?php
/*
FUNCTION formToQuery
PARAMETERS
1) table name
REQUIREMENTS
1) field names should match column names
*/
function formToQuery($tablename)
{
// initialize variables
$query = 'insert into '.$tablename.' set ';
$formdata = '';
$i = 0;
// get field names into $fieldnames array
$fieldnames = array_keys($_POST);
foreach($_POST as $column)
{
$removeProcess = count($_POST)-1;
if($removeProcess>$i)
{
$query .= $fieldnames[$i].'="'.$column.'" ';
$formdata .= $fieldnames[$i].': '.$column.'<br />';
echo '<li>'.count($_POST).'|'.$i.'</li>';
}
$i++;
}
$query .= ';';
echo '<p>'.$query.'</p>';
// SHOW FORM INFO
// echo $formdata;
}
// if button has been pressed
if(isset($_POST['process'])&&$_POST['process']==1)
{
formToQuery('testing');
}
?>
<form name="testing" method="post">
<table>
<tr>
<td>Name:</td><td><input type="text" name="name"></td>
</tr><tr>
<td>Subject:</td><td><input type="text" name="subject"><td>
</tr>
<tr>
<td>Content:</td><td><textarea name="content"></textarea></td>
</tr>
</table>
<input type="hidden" value="1" name="process" />
<input type=submit value="Submit">
</form>
</body>
</html>
simplistik
September 11th, 2007, 06:35 PM
for the zip and phone, i wouldn't force it to be numbers... i would just strip everything that's not and then check length. so you'll essentially be forcing numbers, but in a different way.
imagined
September 12th, 2007, 01:00 PM
DHDESIGN... I didn't quite get the MD5 part and the DATE part. Could you explain please?
I have been trying to encrypt the passwords before inputting them into a database, but my login script never works. So I input the password exactly as it is, no encryption. I know this is a security problem, but if you have any good info on this I will appreciate it.
Simplistik... so you mean that if somebody inputs 956-555-6677 as the phone number, to strip the -'s and end up with 9565556677???
I modified the function. If you just copy, paste it and save it as a php file you should see how it works.
Now, the form displays a div with the error messages. I'm trying to figure out a way to have the fields already filled out with the information submitted in case there are errors so the users can correct it. Is there a way to do this by just using this function? Maybe some javascript? Any suggestions?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<?php
/*
FUNCTION formToQuery
PARAMETERS
1) table name
REQUIREMENTS
1) field names should match column names.
Note that the required field name would strip the 'required' part before getting into the query string.
Ex. nameRequired would pass to the query as column 'name'.
2) required fields should contain 'required' as part of the field name. Ex. requiredName field would be required.
Note that the required field name would strip the 'required' part before getting into the query string.
Ex. nameRequired would pass to the query as column 'name'.
3) email fields should contain 'email' as part of the field name in order to be validated as an email address.
*/
function formToQuery($tablename)
{
// initialize variables
$query = 'insert into '.$tablename.' set ';
$formdata = '';
$i = 0;
$errors = '<ul>';
// get field names into $fieldnames array
$fieldnames = array_keys($_POST);
foreach($_POST as $column)
{
$removeProcess = count($_POST)-1;
if($removeProcess>$i)
{
// ----- >>>>> START VALIDATION <<<<< -----
// ----- if the field should contain an EMAIL address -----
if(eregi('email',$fieldnames[$i]))
{
$pattern = '/.*@.*\..*/';
if(!preg_match($pattern, $column) > 0)
{
// error
$errors .= '<li>Please enter a valid email address.</li>';
}
}
// ----- if field is REQUIRED -----
if(eregi('required',$fieldnames[$i]))
{
// strip whitespace
$column = trim($column);
if($column == '')
{
$requiredfield = str_replace('required', '', $fieldnames[$i]);
$requiredfield = strtoupper($requiredfield);
// error
$errors .= '<li>'.$requiredfield.' is required.</li>';
}
}
// prepare field name for query string
$fieldname = str_replace('required', '', $fieldnames[$i]);
// build query
$query .= $fieldname.'="'.$column.'" ';
// add info to $formdata variable to display it
$formdata .= $fieldnames[$i].': '.$column.'<br />';
// ----- >>>>> END VALIDATION <<<<< -----
}
$i++;
}
$query .= ';';
$errors .= '</ul>';
/* !!!!
PENDING:
IF DATE
DATECREATED DATEMODIFIED
DIGITS ONLY
IF PASSWORD
IF IMAGES
IF ERRORS RETURN THE FORM WITH THE INFORMATION FILLED OUT
check if field names match column names
!!!! */
if($errors == '<ul></ul>')
{
// process query !!!!
}
else
{
echo '<div style="color:#C00; background-color:#FFC;">'.$errors.'</div>';
}
// DISPLAY FORM INFO
echo '<p>'.$formdata.'</p>';
// DISPLAY QUERY
echo '<p>'.$query.'</p>';
}
// if button has been pressed
if(isset($_POST['process'])&&$_POST['process']==1)
{
formToQuery('testing');
}
?>
<form name="testing" method="post">
<table>
<tr>
<td>Name:</td><td><input type="text" name="requiredname"></td>
</tr>
<tr>
<td>Email:</td><td><input type="text" name="email"></td>
</tr>
<tr>
<td>Subject:</td><td><input type="text" name="subject"><td>
</tr>
<tr>
<td>Content:</td><td><textarea name="content"></textarea></td>
</tr>
</table>
<input type="hidden" value="1" name="process" />
<input type=submit value="Submit">
</form>
</body>
</html>
imagined
September 12th, 2007, 01:22 PM
What do you think about this idea?
Having the field names as a parameter for the function and the function will also CREATE the form, that way I could embed something on the field that will fill it out automatically in case there are any errors so the user can correct it, instead of just showing the whole form blank and having the user fill it out again.
What do you think?
DHDesign
September 12th, 2007, 03:21 PM
well, for the MD5 & DATE part...that part of the code actually calls a function (which i posted after the first post) called testforword. what this function does is see if a certain word is within the form fields name...for example, when i develop db apps, everything with a date in it is SOMENAME_DATE, SOMEOTHERNAME_DATE (ie. Inquiry_Date, Call_Date, etc.)...so the validation would take all fields that have the word Date in them, and then either validate the information or make changes to it (such as reformatting the date).
In the case of the password, if the form field name is AdminPass (which is what i just called it), then take that value, md5 it with the md5 function and then store it in the database (so that its encrypted). then when a user logs in, just in ur query write something like:
$query = mysql_query("SELECT * FROM User_Tbl WHERE Username = $username AND Password = md5($password)");
make any sense?
simplistik
September 12th, 2007, 04:04 PM
Simplistik... so you mean that if somebody inputs 956-555-6677 as the phone number, to strip the -'s and end up with 9565556677???
Right, the purpose of it is to make it easier to check the string as well as enforce consistent formatting. So for instance, you put in 111-222-3333 or 111.222.3333 or (111) 222-3333, etc. No matter what they put in it'll strip all that crap. This way in the DB it just looks like a string of 10 or 11 numbers. When you echo it out you can force the consistency, instead of expecting 100 different people to format the number the exact same way. SO you can make 1112223333 or 12223334444 look like (111) 222-3333 or 1 (800) 333 4444.
imagined
September 12th, 2007, 06:29 PM
Simplistik... thanks, I already edited the function to strip the only numbers required field.
DHDESIGN... thanks, I think I already added the password encryption, I just have to test it on the database. about the date, I still need to add some date formatting for input on mysql.
Do you have any suggestions as to how refill the fields in case there is some errors and the page is reloaded?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP LAB</title>
<link rel="stylesheet" type="text/css" href="global.css">
</head>
<body>
<?php
/*
FUNCTION formToQuery
PARAMETERS
1) table name
2) page to direct after the query is successful
REQUIREMENTS
1) field names should match column names.
Note that the required field name would strip the 'required' part before getting into the query string.
Ex. nameRequired would pass to the query as column 'name'.
2) required fields should contain 'required' as part of the field name. Ex. requiredName field would be required.
Note that the required field name would strip the 'required' part before getting into the query string.
Ex. nameRequired would pass to the query as column 'name'.
3) email fields should contain 'email' as part of the field name in order to be validated as an email address.
4) if field must cointain only numbers include 'number' as part of the field name
5) table must contain columns DATECREATED and DATEMODIFIED
6) do not name any column DATE
7) should have a database connection
PENDING
fix $_FILES
check if field names match column names
*/
function formToQuery($tablename, $location)
{
// initialize variables
$query = 'insert into '.$tablename.' set ';
$formdata = '';
$errors = '<ul>';
$i = 0;
// get field names into $fieldnames array
$fieldnames = array_keys($_POST);
foreach($_POST as $column)
{
$removeProcess = count($_POST)-1;
if($removeProcess>$i)
{
// ----- >>>>> START VALIDATION <<<<< -----
// ----- if field is REQUIRED -----
if(eregi('required',$fieldnames[$i]))
{
// strip whitespace
$column = trim($column);
if($column == '')
{
$requiredfield = str_replace('required', '', $fieldnames[$i]);
$requiredfield = strtoupper($requiredfield);
// error
$errors .= '<li>'.$requiredfield.' is required.</li>';
}
}
// ----- if the field should contain an EMAIL address -----
if(eregi('email',$fieldnames[$i]))
{
$pattern = '/.*@.*\..*/';
if(!preg_match($pattern, $column) > 0)
{
// error
$errors .= '<li>Please enter a valid email address.</li>';
}
}
// ----- if the field should contain ONLY NUMBERS -----
if(eregi('number',$fieldnames[$i]))
{
$column = preg_replace('|[^0-9]|', '', $column);
}
// ----- if form field is a DATE -----
if(eregi('date',$fieldnames[$i]))
{
if($column!="")
{
// !!!!!!!! FORMAT THE DATE FOR MYSQL
// $format = 'd-m-y';
}
}
// ----- if the field is a PASSWORD
if(eregi('password',$fieldnames[$i]))
{
$column = 'md5('.$column.')';
}
// prepare field name for query string
$fieldname = str_replace('required', '', $fieldnames[$i]);
$fieldname = str_replace('number', '', $fieldnames[$i]);
// build query
$query .= $fieldname.'="'.$column.'" ';
// add info to $formdata variable to display it
$formdata .= $fieldnames[$i].': '.$column.'<br />';
// ----- >>>>> END VALIDATION <<<<< -----
}
$i++;
}
// ----- if there are FILES to be uploaded -----
// get field names into $fieldnames array
$fieldnames = array_keys($_FILES);
$i = 0;
foreach($_FILES as $column)
{
$file = $fieldnames[$i];
if(!empty($_FILES[$file]['tmp_name']))
{
// !!!!!!!! FIND WAY TO NAME THE FILES
// build query
$query.= $fieldnames[$i].'="'.$_FILES[$file]['name'].'" ';
// add info to $formdata variable to display it
$formdata .= $fieldnames[$i].': '.$_FILES[$file]['name'].'<br />';
}
$i++;
}
$query .= 'datecreated = CURDATE(), datemodified = CURDATE();';
$errors .= '</ul>';
if($errors == '<ul></ul>')
{
// process query !!!!
}
else
{
echo '<div style="color:#C00; background-color:#FFC;">'.$errors.'</div>';
}
// DISPLAY FORM INFO
echo '<p>'.$formdata.'</p>';
// DISPLAY QUERY
echo '<p>'.$query.'</p>';
if(!mysql_query($query))
{
exit('<div style="color:#C00; background-color:#FFC;">Error performing query.</div>');
}
else
{
header('location:'.$location);
}
}
// if button has been pressed
if(isset($_POST['process'])&&$_POST['process']==1)
{
formToQuery('testing');
}
?>
<form name="testing" method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>Date:</td><td><input type="text" name="inputdate" maxlength="8"><br />DD-MM-YY</td>
</tr>
<tr>
<td>Name:</td><td><input type="text" name="requiredname"></td>
</tr>
<tr>
<td>Password:</td><td><input type="password" name="password"></td>
</tr>
<tr>
<td>Re-enter Password:</td><td><input type="password" name="repassword"></td>
</tr>
<tr>
<td>Email:</td><td><input type="text" name="email"></td>
</tr>
<tr>
<td>Phone:</td><td><input type="text" name="phonenumber"></td>
</tr>
<tr>
<td>Subject:</td><td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Upload file:</td><td><input type="file" name="photo"></td>
</tr>
<tr>
<td>Content:</td><td><textarea name="content"></textarea></td>
</tr>
</table>
<input type="hidden" value="1" name="process" />
<input type=submit value="Submit">
</form>
</body>
</html>
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.