What should I do first, bind a parameter or apply a filter? PHP

78 views Asked by At

For example, I need to use digits for input from a url-based query

So I want to use ctype_digit to make sure that the queries are only numbers, and if I were to bind the parameter just to be safe, which one should I do first, or is it redundant to do both?

I currently have this implemented on a garbage-site (something I lazily put together)

I bind the parameter from the parsed-url then within the results (after the bind part)

I display the entry if the id is a digit, this sounds stupid I know like what the hell am I thinking? I don't know.

I should have ctype_digit it before I bound it, or none at all... I don't get what bind_param does, I looked at the manual...

Binds variables to a prepared statement as parameters

That's all that it does, no filtering?

2

There are 2 answers

0
venca On

The correct workflow is:

  1. Filter input data ($_GET, $_POST, file...)
  2. Validate input
  3. On success insert/update/delete to db
  4. Otherway usually display error message
0
Eddy On

As @venca stated, you want to:
1. Filter input data
2. Validate input
3. Perform your transaction.

Always begin by filtering your input. Optionally, you can compare the result of your filtered input to the original, and if they are different, inform the user that they put in bad data.

To answer your question on Binding a variable to a prepared statement, first understand what a prepared statement is. A prepared statement is a SQL string with the parameters missing, such as:
SELECT Name FROM employees WHERE ID='?';
In this case, if a user were to add an SQL injection, the whole injection is treated as a string to look for rather than a part of the SQL command. For some simple information on this, see How can I prevent SQL-injection in PHP? Also, there are tutorials available that get you started, such as this short one on w3schools on how to use prepared statements in PHP.