0

I want to check if there's a row with a specific value in a specific column.

I will check many columns, so I decided to create a function, for everything instead of creating a function specific for each thing.

    public function checkInfo($column, $parm)
    {
        $this->check = $this->pdo->prepare("SELECT * FROM recoveries WHERE :column = :parm");
        $this->check->execute(array( ":column" => $column, ":parm" => $parm ));

        if ($this->check->rowCount())
        {
            return true;
        }
        else
        {
            throw new exception ("Could not find recovery ".$parm.", ".$column."");
        }
    }

Variable column: The column name.

Variable parm: The parm name (Whatever the user posted in the form).

And that's how I check if its row count:

    $column = 'recovery_email'; 
    try
    {
        $recover->checkInfo('recovery_email', $_POST['email']);
        echo
        '
            <form action="check.php" method="post">
                <input type="text" name="id">
                <button type="submit" class="btn">Continue</button>
            </form>
        ';
    }
    catch (Exception $t)
    {
        echo '<div class="alert alert-error">'.$t->getMessage().', <a href="check.php">Go back</a></div>';
    }

Result:

 Could not find recovery
  • The column names are correct.
  • And the Parm is correct (Took it from the database).

Problem:

I am putting the correct information, yet it giving me an error that could not find the row.

Question

Why is it happening?

How can I fix this?

Jony Kale
  • 111
  • 1
  • 1
  • 5
  • 2
    Duplicate of [Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?](http://stackoverflow.com/questions/15990857/reference-frequently-asked-questions-about-pdo#15991422) – Your Common Sense May 05 '13 at 18:06
  • @Your Common Sense Oh, so I have to escape it myself? '".$column."' ? – Jony Kale May 05 '13 at 18:08

1 Answers1

0

You cannot bind column names. Bound parameters work only with values.

But even if you could - even a syntactically valid column name would produce an SQL error if the column didn't exist in your table.

  • First, check if the column exists and is allowed to be queried. There are many ways to do this - the simplest is to use the in_array function.

  • Then insert column name into your SQL statement via string concatenation (or interpolation), and bind only column value.

Your method would look like this:

public function checkInfo($column, $parm)
{
    if(!in_array($column, array('recovery_email', 'my_column2', 'my_column3')))
    {
        throw new exception ("Unknown column: ".$column);
    }

    $this->check = $this->pdo->prepare("SELECT * FROM recoveries WHERE $column = :parm");
    $this->check->execute(array( ":parm" => $parm ));

    // ... 
}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103