-3

I have this PHP function that I want to get data from a database just by calling get_database_data()

In this function I have two variables that should be used in WHERE $variable1 = $variable2.

I know you could use "WHERE ".$variable1." = ".$variable2. It's works with $variable2, but not $variable1.

Something else I could use, or how do I make this work?

EDIT:

There is no errors, but the row I don't get any rows returned

EDIT2:

I've got it to work, using: "WHERE $variable1 = ".$variable2

Padnezz
  • 89
  • 1
  • 2
  • 10

1 Answers1

0

You should use prepared statements.

Here is a snippet that can be used to form a function that can return the data you need. You should be able to modify this quite easily to your needs.

   function get_database_data($variable1,$variable2)
   {
        $dbh = new PDO("mysql:host=url;dbname=somedb", "user", "pass");
        $sqlUpdate = "SELECT * FROM sometable WHERE {$variable1} = :variable2";
        $sthUpdate = $dbh->prepare($sqlUpdate);
        $sthUpdate->bindParam(':variable2', $variable2, PDO::PARAM_STR, 12);
        $sthUpdate->execute();
        $result = $sthUpdate->fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }



    print_r(get_database_data('fieldname','value'));

I found this question quite interesting and would suggest you give it a read also:

Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?

Community
  • 1
  • 1
The Humble Rat
  • 4,586
  • 6
  • 39
  • 73