The specific description of the two methods in the PDOStatement class is as follows
bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )<pre name="code" class="php">bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
Difference 1: bindParam is to bind a parameter to the specified variable name, and bindValue is to bind a value to a parameter
<pre name="code" class="php">$db = new PDO('mysql:host=localhost;dbname=dbtest;charset=utf8','user','pass'); $st = $db->prepare('select * from tabletest where id = ?'); $id = 1; $st->bindParam(1,$id,PDO::PARAM_INT); //$st->bindValue(1,$id,PDO::PARAM_INT);
$db = new PDO('mysql:host=localhost;dbname=dbtest;charset=utf8','user','pass'); $st = $db->prepare('select * from tabletest where id = ?'); $st->bindParam(1,1,PDO::PARAM_INT); //$st->bindValue(1,1,PDO::PARAM_INT);
bindParam will report the following error, but bindValue can be executed normally
Fatal error: Cannot pass parameter 2 by reference
Difference 2: Unlike PDOStatement::bindValue(), variables in PDOStatement::bindParam() are bound as references and are only called in PDOStatement::execute() The value is taken only when
$db = new PDO('mysql:host=localhost;dbname=dbtest;charset=utf8','user','pass'); $st = $db->prepare('select * from tabletest where id = ?'); $id = 1; $st->bindParam(1,$id,PDO::PARAM_INT); $id = 2; $st->execute(); $rs = $st->fetchAll(); print_r($rs);
$db = new PDO('mysql:host=localhost;dbname=dbtest;charset=utf8','user','pass'); $st = $db->prepare('select * from tabletest where id = ?'); $id = 1; $st->bindValue(1,$id,PDO::PARAM_INT); $id = 2; $st->execute(); $rs = $st->fetchAll(); print_r($rs);
Although both can complete the binding of sql parameters, there are still differences between the two. In practical applications, we should choose the one that suits us. Here is an example of improper use of bindParam
Suppose there is a data table with shaping There are two fields, id and string name, and there is an array of data $params = array(1,'Zhang San') ready to be inserted using preprocessing. The specific code is as follows
$db = new PDO('mysql:host=localhost;dbname=dbtest;charset=utf8','user','pass'); $st = $db->prepare('insert into tabletest(id,name) values(?,?)'); $params = array(1,'张三'); foreach($params as $k => $v){ $index = $k + 1; $st->bindParam($index,$v); } $st->execute();
insert into tabletest(id,name) values(1,'张三');
insert into tabletest(id,name) values('男','男');
The above introduces the difference between the bindParam and bindValue methods of the PDOStatement class in php pdo, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.