Help with function using a list


#1

I’m trying to take this and turn it into a function using a list figured I could loop through that list. Instead of writing the same line multiple times but each line having slight differences.

 $FirstName = mysqli_real_escape_string($conn, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($conn, $_POST['LastName']);
$Email = mysqli_real_escape_string($conn, $_POST['Email']);
$Username = mysqli_real_escape_string($conn, $_POST['Username']);
$Passphrase = mysqli_real_escape_string($conn, $_POST['Passphrase']);
$ConfirmEmail = mysqli_real_escape_string($conn, $_POST['ConfirmEmail']);
$ConfirmPassphrase = mysqli_real_escape_string($conn, $_POST['ConfirmPassphrase']);

Here is my list.

$FieldValues = array(‘FirstName’, ‘LastName’, ‘Email’, ‘Username’, ‘Passphrase’, ‘ConfirmEmail’, ‘ConfirmPassphrase’);

$vars = list($FirstName, $LastName, $Email, $Username, $Passphrase, $ConfirmEmail, $ConfirmPassphrase) = $FieldValues;

And this is my function which is currently not working.

function RetriveFieldValues() {
while ($vars = each($FieldValues)) {
$vars = mysqli_real_escape_string($conn, $_POST[$FieldValues]);
}
}


#2

A) There’s a much simpler way of dealing with data being supplied to an sql query statement. Use prepared queries, with a place-holder in the sql query statement for each value, then supply the value(s) when you execute the query. Doing this eliminates the need for any xxxx_escape_string() function, which simplifies the php code, and this also simplifies the sql query syntax (the variables, single-quotes around the variables, any concatenation dots, and any {} are all removed.) Further, if you use the much simpler php PDO extension, use implicate binding by supplying an array of input data to the execute() call, and use exceptions to handle database statement errors, you will end up with almost no php code compared with what you may have seen or been using in the past.

B) If you do have a need to apply a function to a SET of data, use array_map(). Too many people are stuck on creating discrete variables, one for each possible form field. This is a waste of typing, creating bespoke code that has to be written/changed for each different form. Instead, just treat the data as a set and use php’s array functions to operate on the data. To apply a function/method to each value in an array, for mysqli_real_escape_string (which you won’t need any more with prepared queries), do this -

$post = array_map([$conn,'real_escape_string'],$_POST);

Another example which would trim() all the data at once -

$post = array_map('trim',$_POST); // note: if any of the form fields can be arrays, you would write a recursive call-back function to use instead of php's trim() function

At this point you would references elements in the $post array in the rest of the code - $post[‘FirstName’], $post[‘LastName’], …


#3

@phdr

Thanks that was quite a bit of information. And I have not thought about it that way. I like to get the thoughts of somebody other than myself.

If I do it using your A) option. Does that mean I could also get rid of the list and the array? I am using mysqli I tried PDO but didn’t have much luck in it. I should probably go back and have a look at PDO. After reading your post I am considering going back and writing my whole project using PDO and prepared queries.

What are the advantages of using PDO? The only one that I had seen is it can be used with multiple database systems. If you would want to switch to another database system you would just have to change your connection string and queries. Other than that I am not vary familiar with it.

When I write code I try to only add what is necessary and nothing more. But I try to think of other ways to do it and just end up making it more complicated that what it actually it. And is PDO procedural or is it object oriented?


#4

The php mysqli extension is overly complicated and inconsistent (dealing with prepared and non-prepared queries is completely different and one thing they did to try an make them the same is not portable between servers and should not be used.) The php PDO extension takes less lines of code to accomplish a prepared query and you can deal with the result from any query in the same way, as a PDOStatement object.

Your $FieldValues array, which is actually the field names or field definitions, can be the basis for dynamically processing the form data, using a practice called a “data driven design”, where you have a data structure defined somewhere (database table, array) that controls what general purpose code does.

A simple example would be to define which of the fields are ‘required’ (must not be an empty string.)

// define the expected form fields and any dynamic processing attributes
$Fields = [];
$Fields['FirstName'] = ['label'=>'First Name','required'=>true];
// repeat the above for each form field

The ‘label’ element is used when forming error messages… You would set the ‘required’ element to either a true or false value to control what the ‘required’ validation logic does.

In the form processing code, you can then simply loop over the defining array and validate the input data.

// 'required' validation logic
foreach($Fields as $field=>$arr)
{
	if(isset($arr['required']) && $arr['required'] && $post[$field] == '')
	{
		$errors[$field] = "{$arr['label']} is required.";
	}
} 

You can expand the $Fields defining array to handle other validation steps (by listing call-back functions), and to handle CRUD (Create, Read, Update, Delete) operations to dynamically build sql queries with the appropriate/allowed fields for each type of query.

PDO is OOP only, which again is shorter, less typing, then procedural. You don’t have to understand OOP to use the PDO extension. Calling an OOP method is just of the format - $some_var = $object_instance->method_name($input_parameters); To call the PDO prepare method would be - $stmt = $pdo->prepare($sql);, where $pdo is variable holding the instance(database connection) of the PDO class.


#5

@phdr

Thanks again for the information. I’m going to have to look more into data driven design. I have never done anything like that. It sounds vary interesting. If you don’t mind me asking do you write your web apps using a framework or do you write it from scratch.


#6

For your PDO research


#7

@astonecipher

Thanks for the information. I’m going to go a little bit off topic from the function. Was wondering if you could tell me what is the best way to go about this. Working on a web app in PHP been writing it from scratch. I am the only one working on it. What would be the best way to write my project so I can have templates and such. Would like to not have to write everything from scratch I can do most of it. Be there is probably something open source out there that I can use for parts of it. And what is a good structure a med to large project. My project will have my databases, search, login, registration, vote, and a blog. (The blog is for the admin like myself to post updates and new features about the project. And the vote is for users to vote on new features.) Figured I would be able to post the blog and the vote through the administration page. But I don’t want to write the administration page, vote, and blog from scratch. The rest of it I can do from scratch.


#8

What you are describing sounds a lot like WordPress base functionality, but your learning so I get it.

I would focus on classes and OOP styles. Or learn about modular programming in general. Define what your core code needs to be, things like the database connection. Then start working on the side processes you want to add, search, login/ registration, voting, blogs.