homepage Welcome to WebmasterWorld Guest from 54.227.77.237
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Dynamic PHP Validation
Is it possible? I keep receiving errors.
max4




msg:3930562
 5:11 pm on Jun 10, 2009 (gmt 0)

Hello,

It was suggested to me, in a previous post, that I use while() loops to verify data against the database instead of switch statements which is what I currently use. A typical switch statement looks something like this:
[fixed]
$x = array();
switch($_POST['example'])
{
case 0:
case 15:
case 16:
case 17:
case 18:
$x['example'] = $_POST['example'];
break;
}
[/fixed]

It was suggested that I do the following instead:
[fixed]
$name_row = mysql_fetch_object($name_results);
while($value_row = mysql_fetch_object($value_results))
{
if ($_POST['$name_row->name'] == $value_row->value)
{
$x['$name_row->name'] = $_POST['$name_row->name'];
}
}
[/fixed]

Further down my script I check to see if $x['example'] !== $_POST['example'], and if it isn't; I send the user back to the form and return a validation error.

My switch statement works fine. If a correct value is selected then no error is returned; however, the while() loop always returns the validation error, regardless of whether or not a correct value was sent. I ran several tests on a self-submitting form (note, the actual form is not self-submitting) and used print_r to see what was going on. print_r($name_row->name); always returns the correct name, however when I try something like this:
[fixed]
$_SESSION['$name_row->name'] = $_POST['$name_row->name'];
[/fixed]

I get an undefined error on $name_row->name. I've tried using different functions as well, I've cycled through all of the mysql_fetch functions as well as exploding the data into an array and nothing seems to work. Can this be done?

 

nick279




msg:3930573
 5:23 pm on Jun 10, 2009 (gmt 0)

Not sure if I've got this right - could you post the code which is directly before the mysql_fetch ....

You could put the data into an array and just use in_array() - seems like it could be a bit easier

If it's a large app with multiple users you may need to use mysql - otherwise I'd use the in_array method

$valid = array(1,2,3,4,5,6);
if(in_array($_POST['example'],$valid)) $x['example'] = $_POST['example'];

max4




msg:3930596
 5:45 pm on Jun 10, 2009 (gmt 0)

I tried using the array method by populating the array with values from the database; that also failed to work. I kept receiving a notice that I am converting an array to string - even though I use that same bit of code elsewhere on my site with no problems. Here is the full function:
[fixed]
function validate_values() {
$name_results = mysql_query("SELECT column FROM `table` WHERE column = 4");
$value_results = mysql_query("SELECT column, column FROM `table` WHERE column = 4");
if(mysql_num_rows($name_results) > 0 && mysql_num_rows($value_results) > 0)
{
$name_row = mysql_fetch_object($name_results);
while($value_row = mysql_fetch_object($value_results))
{
if ($_POST['$name_row->name'] == $value_row->value)
{
$x['$name_row->name'] = $_POST['$name_row->name'];
}
}
}
else
{
header("Location: example.php");
}
}
[/fixed]

The variable $x is defined before I call validate_values() on the action script. Any ideas?

nick279




msg:3930620
 6:01 pm on Jun 10, 2009 (gmt 0)

It looks like your SQL code isn't right? You'll get errors running that code. Have you substituted the words 'column' and 'table' with the actual column and table names, or are you running what you pasted in this thread?

Can you just explain what it is you are trying to do in bullet form?

e.g.

- submit form
- search for ? from database

do you have a table of users?
are you checking a password of some sort?

max4




msg:3930640
 6:26 pm on Jun 10, 2009 (gmt 0)

Hi Nick, thanks for the reply. No, I am not using column and table. I threw that up there as part of the example.

In list form:

1) Gather values from database
2) Check to see if submitted values match those in the database
3) If they do, place the selected value in an empty array for further processing.

The submitted values from number two come from dynamically populated select menus generated within and as a part of my forms. The forms submit to an external action script. The users table is a completely separate entity from the tables holding the values in question. Thanks.

nick279




msg:3930648
 6:33 pm on Jun 10, 2009 (gmt 0)

I want to help you solve this problem, can you tell me what the two tables are for? (and if/how they interact)

max4




msg:3930656
 6:39 pm on Jun 10, 2009 (gmt 0)

I appreciate your quick responses, Nick; thank you very much for your time in this matter. The two lines refer to two tables in my database, one table holds select menu names and the other table holds select menu values. I use those two tables to dynamically populate all select menus and checkboxes on my site.

Because the values being submitted by the users come from those two tables, it makes sense then to check the submitted values from the user against the values in the database rather than hard coding the values in switch statements. The benefit of this is nothing breaks if database values are altered. I also use ON CASCADE RESTRICT to ensure that the main table is not altered in anyway as to fully preserve my data.

nick279




msg:3930677
 6:58 pm on Jun 10, 2009 (gmt 0)

Ok getting there now :)

- User comes to a select box
- This select box has a "name" e.g. name="color" (populated from a table `names`)
- This select box has a number of values e.g. "red","blue" (populated by a table `values`)
- You want to verify that `name` is a `value` e.g. `red` is a `color` on submit
- If the value is/not return true/false

Would it be safe to say you have a nameid field or something similar in your values table

max4




msg:3930691
 7:12 pm on Jun 10, 2009 (gmt 0)

Yes. The name table contains two columns, an ID column and a name column. The name table is the parent table of the two. The ID column is an integer that is referenced in the child table. The child table has three columns, value, name and ID. ID is properly referenced to ID in the parent table.

nick279




msg:3930713
 7:36 pm on Jun 10, 2009 (gmt 0)

OK

$val = mysql_escape_string($_POST['value']);
$query = <<<SQL
SELECT *
FROM `names`, `values`
WHERE `names`.`id` = `values`.`nameid`
AND `values`.`value` = '{$val}'
SQL;
$res = mysql_query($query);

if(mysql_num_rows($res))
{
// true
$row = mysql_fetch_object($res);
print_r($row); // will show you contents
}

else
// false

max4




msg:3930720
 7:44 pm on Jun 10, 2009 (gmt 0)

Wow, you've avoided the while loop altogether. I'm impressed by your logic, thank you. I am a little confused by this '$query = <<<SQL.' Could you please explain this syntax?

nick279




msg:3930744
 8:03 pm on Jun 10, 2009 (gmt 0)

sure

it basically makes a string between

echo <<<WORD

WORD;

instead of having to concatenate

(you can also put {$variables}) in there.

max4




msg:3930763
 8:24 pm on Jun 10, 2009 (gmt 0)

I have not see this syntax before, I appreciate you bringing it to my attention. I am familiar with the curly brackets though so I can understand what is going on. Again, thank you for the time and help; I really appreciate it.

coopster




msg:3931161
 12:14 pm on Jun 11, 2009 (gmt 0)

Side note: it's called heredoc syntax.
Strings [php.net]

max4




msg:3931717
 2:09 am on Jun 12, 2009 (gmt 0)

Thank you coopster.

I have another question. I have a form with multiple checkboxes whose values form a single array when submitted. This group of checkboxes is dynamically populated from data stored in my database. This is what I am trying to accomplish:

1) User selects a few checkboxes and hits submit.
2) The checkboxes are organized and formatted into a usable array.
3) The array is processed and each value within the array is checked against values in the database.
4) If a single value does not match a database value, a validation error is returned. This is what I have so far:
[fixed]
//This is how the checkboxes are set up:
<input type="checkbox" name="example[]" value="371" />
[/fixed]
[fixed]
//And this is the validation process:
if (isset($_POST['example'])) {
$array=implode(",",$_POST['example']);
$val = mysql_real_escape_string($array);
$value_results = mysql_query("SELECT value FROM `values` WHERE ID = 23 AND value IN('{$val}')");
if(mysql_num_rows($value_results) > 0) {
// Success
}
else {
// Error
}
}
[/fixed]

This method works, but with one major flaw. I have set up an 'invalid' checkbox with a malicious value like so:
[fixed]
//This is how the checkboxes are set up:
<input type="checkbox" name="example[]" value="371'; mysql_query("INSERT INTO values (value, name, ID) VALUES (517,'Injection',33)");#" />
[/fixed]

The query doesn't execute because I am using the mysql_real_escape_string() function, but the array is validated because one true value was passed. As you can imagine, this is not desired. Any ideas? Thanks.

max4




msg:3932242
 5:16 pm on Jun 12, 2009 (gmt 0)

I'm getting closer, but still no cigar. I'm trying out while loops and foreach loops. The problem is that getting an array from a MySQL result that holds multiple records does not create a single array and extracting the information through a while loop creates separate arrays for each record. Because of this, the in_array function is useless unless checking against only one checkbox value.

Of course, I need a way to check against multiple checkbox values; so another method is required. Does anyone know how to separate two arrays into independent values and then run each array value side by side? If I can do this, then this problem is solved.

nick279




msg:3932263
 5:40 pm on Jun 12, 2009 (gmt 0)

if(array_key_exists("example",$_POST)) // to avoid notices/errors
{

foreach($_POST['example'] as $val)
{

$value = mysql_escape_string($val);
$query = "SELECT * FROM `values` WHERE `id` = '{$value}'";
$res = mysql_query($query);
if(!mysql_num_rows($res))
{//fail}

}

}

max4




msg:3932285
 6:10 pm on Jun 12, 2009 (gmt 0)

Thanks again, nick. This method still does not account for a checkbox like this:
[fixed]
<input type="checkbox" name="example[]" value="371'; mysql_query("INSERT INTO values (value, name, ID) VALUES (517,'Injection',33)");#" />
[/fixed]

I'll admit, your method is a lot cleaner and simpler than what I'm working with now. I might have to use preg_replace with your method to remove any invalid characters. I'll work with it some more and post back with my final results. Again, thanks nick; I really appreciate it.

nick279




msg:3932301
 6:26 pm on Jun 12, 2009 (gmt 0)

$value = mysql_escape_string($val);

if($value < 1 ¦¦ $value > 10000) // fail

max4




msg:3932349
 7:58 pm on Jun 12, 2009 (gmt 0)

Hi Nick, thanks again for the help! That did not work, but the following works like a charm:
[fixed]
if(!preg_match("/^[0-9\ ]+$/",$val)) {
echo 'Error, values are fake!<br />';
break;
} else {
echo 'Value is real!<br />';
}
[/fixed]

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved