Differences between PHP PDOStatement objects bindpram of bindvalue of and bindcolumn
- 2021-08-03 09:50:02
- OfStack
PDOStatement:: bindParam--Bind a parameter to the specified variable name.
Bind 1 PHP variable to the corresponding named placeholder or question mark placeholder in the SQL statement used as preprocessing. Unlike PDOStatement:: bindValue (), this variable is bound as a reference and takes its value only when PDOStatement:: execute () is called.
PDOStatement:: bindValue--Bind a value to a parameter.
Bind 1 value to the corresponding named placeholder or question mark placeholder in the SQL statement used as preprocessing.
<?php
$stm = $pdo->prepare("select * from users where user = :user");
$user = "jack";
// Correct
$stm->bindParam(":user",$user);
// Errors
$stm->bindParam(":user","jack");
// Correct
$stm->bindValue(":user",$user);
// Correct
$stm->bindValue(":user","jack");
// So use bindParam Is the first 2 Parameters can only use variable names, not variable values, and bindValue To you can use specific values.
?>
PDOStatement:: bindColumn--Bind a column to an PHP variable.
Arranges a specific variable to bind to a given column in a query result set. Each call to PDOStatement:: fetch () or PDOStatement:: fetchAll () updates all variables bound to the column.
<?php
function readData ( $dbh ) {
$sql = 'SELECT name, colour, calories FROM fruit' ;
try {
$stmt = $dbh -> prepare ( $sql );
$stmt -> execute ();
/* Bind by column number */
$stmt -> bindColumn ( 1 , $name );
$stmt -> bindColumn ( 2 , $colour );
/* Bind by column name */
$stmt -> bindColumn ( 'calories' , $cals );
while ( $row = $stmt -> fetch ( PDO :: FETCH_BOUND )) {
$data = $name . "\t" . $colour . "\t" . $cals . "\n" ;
print $data ;
}
}
catch ( PDOException $e ) {
print $e -> getMessage ();
}
}
readData ( $dbh );
?>