2

I was reader about PDO , and I was wondering what is the deference between those two methods:

public function query($sql)
    {
        $req = $this->db->prepare($sql);
        $req->execute();
        return $req->fetchAll(PDO::FETCH_OBJ);
    }

public function query($sql, $data  = array())
    {
        $req = $this->db->prepare($sql);
        $req->execute($data);
        return $req->fetchAll(PDO::FETCH_OBJ);
    }

In the second method, execute has an empty array as a parameter and the first one doesn't, what is the role of using an empty array as a parameter for execute ?

3
  • people can always pass second parameter in second query() function, I can't understand much from this piece of code... Commented Mar 17, 2013 at 13:58
  • Did you post this question after reading the documentation page? It lists there what are the arguments for the method. Maybe something was not clear from there? Commented Mar 17, 2013 at 14:00
  • First one is wrong and second one is right. That's all. Commented Mar 17, 2013 at 14:00

3 Answers 3

1

The array is only empty by default. You can pass values in that array and they will be inserted into your SQL statement appropriately (ie - array key=>field name).

Defining an empty array in the function parameters states that this is an optional parameter and you are not forced to pass it - only when it is relevant. For example, when performing an INSERT command. If you don't pass any value to the $data parameter, it's default value will simply be an empty array.

An example of using default parameters -

function saySomething($text="Hello World!"){
  echo $text;
}

saySomething(); // will echo out the default "Hello World!"
saySomething("Goodbye World!"); // will echo out "Goodbye World!" as specified. 
Sign up to request clarification or add additional context in comments.

Comments

1

First one lets you to run a query without parameters.
Second one lets you to run a query either with parameters or without:

$data = $db->query("SELECT * FROM table"); 
$data = $db->query("SELECT * FROM table WHERE id=?",array($id)); 

both works.

Comments

1

You can add you parameter bindings in an array instead of using the bindParam() function beforehand.

for instance you wanna select something by id

    $stmt = $dbh->prepare("SELECT * FROM `something` WHERE `id` = ?");
    $stmt->execute(array($id));

is the same as

    $stmt = $dbh->prepare("SELECT * FROM `something` WHERE `id` = ?");
    $stmt->bindParam(1, $id, PDO::PARAM_INT, 11);
    $stmt->execute();

Though for the bindParam function you can check better, Check PHP Manual PDO::excute()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.