开发者

PDO: can I avoid bindParam?

开发者 https://www.devze.com 2023-02-14 07:17 出处:网络
I modified this code from somewhere but I am not sure if I am doing it correctly, I use method to insert data int开发者_JS百科o database,

I modified this code from somewhere but I am not sure if I am doing it correctly,

I use method to insert data int开发者_JS百科o database,

# insert or update data
    public function query($query, $params=array())
    {
        try
        {
            $stmt = $this->connection->prepare($query);
            $params = is_array($params) ? $params : array($params);
            $stmt->execute($params);
            return true;
        }
        catch (PDOException $e) 
        {
            # call the get_error function
            $this->get_error($e);
        }
    }

Then I just need to call it like this,

$sql = "
    INSERT root_countries_cities_towns (
        tcc_names,
        cny_numberic,
        tcc_created
    )VALUES(
        ?,
        ?,
        NOW()
    )";

$pdo->query($sql,array('UK','000'));

It works fine perfectly! but I don't understand what this line does - can someone explain please?

$params = is_array($params) ? $params : array($params);

I thought I have to use bindParam to bind the parameters first, but it seems that I don;t have to anymore with is method - is it safe and secure then??

Does it meant that I don't have to prepare the query in this way anymore?

$sql = "
        INSERT root_countries_cities_towns (
            tcc_names,
            cny_numberic,
            tcc_created
        )VALUES(
            :name,
            :numberic,
            NOW()
        )";

and forget about this binding?

$stmt = bindParam(':name','UK', PDO::PARAM_STR);
$stmt = bindParam(':numberic','000', PDO::PARAM_STR);

Thanks.


I guess that's pretty much PHP syntax question rather than PDO one.

$params = is_array($params) ? $params : array($params);

is a shortland (called ternary operator)) for

if (is_array($params)) {
   $params = $params;
} else {
  $params = array($params);
}

which I'd rather wrote as

if (!is_array($params)) $params = array($params);

which is pretty self-explanatory and can be read almost in plain English:

if $params is not an array, let's make it array with one value of former $params

That's why I hate ternary operator (and lambdas) and always avoid it's use. It makes pretty readable code into a mess. Just out of programmer's laziness.

To answer your other questions,

Does it meant that I don't have to prepare the query in this way anymore?

Who said that? You're preparing it all right in your code, check it again.

and forget about this binding?

that's true. execute($params) is just another way to bind variables.


the line

$params = is_array($params) ? $params : array($params);

is simply checking if the $params variable is an array, and if so, it creates an array with the original $params value as its only element, and assigns the array to $params.

This would allow you to provide a single variable to the query method, or an array of variables if the query has multiple placeholders.

The reason it doesn't use bindParam is because the values are being passed to the execute() method. With PDO you have multiple methods available for binding data to placeholders:

  • bindParam
  • bindValue
  • execute($values)

The big advantage for the bindParam method is if you are looping over an array of data, you can call bindParam once, to bind the placeholder to a specific variable name (even if that variable isn't defined yet) and it will get the current value of the specified variable each time the statement is executed.


The first example transforms the contents of your $params into an array, if it wasn't already an array (for example if only one parameter was passed and it was passed as an individual item instead of as an array of length 1).

The two examples work just as well, except that for the first one, parameters introduced with the array $params are injected where ? are found in the SQL query, whereas in the second one, the formatting of the parameters is actually done by name (you bind a parameter name as found in the sql to an actual parameter).

You should use the first one, it's easier to write.


Passing an array to PDOStatement::execute() passes each entry in the array through PDOStatement::bindParam() (or maybe bindValues()) using defaults (bind type, etc).

Basically, it's as safe as pre-binding.

The advantage to using bindParam is that it binds to the variable reference. This means you can change the value of the variable without re-binding and execute the statement with new values. This is especially useful in a loop, eg

$vals = array('foo', 'bar', 'baz');
$stmt->bindParam(1, $val);
foreach ($vals as $val) {
    $stmt->execute(); // Executes once for each value in $vals
}

I don't understand what this line does - can someone explain please?

That line converts a non-array into an array.

For example

$params = 'foo';
$params = is_array($params) ? $params : array($params);
$params == array('foo');

I imagine it's to facilitate situations where you have only one placeholder and one value to bind as PDOStatement::execute() can only be passed an array.


Try this class. I use PDO a lot and this is what I use all the time for my projects.PHP PDO Class on GitHub

0

精彩评论

暂无评论...
验证码 换一张
取 消