-2

This may seem like a very dumb question, but I don't know if it's possible. I'm trying to write a function as follows:

function checkDuplicates($input) {
    $result = pg_query('SELECT username FROM accounts WHERE LOWER(username)=\''.strtolower(pg_escape_string($input)).'\'') or exit(pg_last_error());
}

and I want to replace "username" with the name of the variable being passed in. For example, if I called checkDuplicates($email), I want essentially the following function to be called:

function checkDuplicates($email) {
    $result = pg_query('SELECT email FROM accounts WHERE LOWER(email)=\''.strtolower(pg_escape_string($email)).'\'') or exit(pg_last_error());
}

Is there any way to do this?

Prangle
  • 13
  • 6
  • You probably need something like references – dGRAMOP Dec 22 '17 at 21:10
  • http://php.net/manual/en/language.references.arent.php – dGRAMOP Dec 22 '17 at 21:11
  • why not to pass string as a param? 0_o – 2oppin Dec 22 '17 at 21:11
  • If you anyway take the effort to name those variables in your code accordingly, you should rather do it something like `function chkDupe($field, $value) {...}` and `chkDupe('email', $input); chkDupe('name', $imput)` etc – marekful Dec 22 '17 at 21:12
  • If you pass an array to the function it can work. Say you have `$input = ['email', 'abc@hotmail.com'];` then you can use [0] as the select and [1] as the search – Andreas Dec 22 '17 at 21:12

1 Answers1

0

You will need to pass the column as a second parameter. Changing your parameter variable name from $input to $email won't actually affect the way in which you call the function.

You can simply do:

function checkDuplicates($col, $val, $return_col) {
    $result = pg_query('SELECT '.$return_col.' FROM accounts WHERE LOWER('.$col.')=\''.strtolower(pg_escape_string($val)).'\'') or exit(pg_last_error());
}

Keep the usual SQL injection dangers in the back of your mind when you're doing this. You may want to run the $col and $return_col input through a whitelist, etc.

RToyo
  • 2,877
  • 1
  • 15
  • 22
  • Can you tell me about SQL injection/point me to some helpful links? – Prangle Dec 22 '17 at 21:20
  • @Prangle See the first **Related** question: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Barmar Dec 22 '17 at 21:48
  • @Prangle The concept of SQL injection is pretty simple. Barmar's link can help you out, but you can also look it up on Google. It's such a simple/common concept that there's no need to give you any specific links. The basic idea is that the variable values you put into your query are interpreted literally when sent to the database as SQL, and problems can arise. Imagine if `$return_col` in the query above had a value of `1; UPDATE accounts SET password='123456'`. Injections don't have to be malicious either - simple typos or chars can cause unexpected bugs and stuff too. – RToyo Dec 22 '17 at 22:32