9

代码示例

$query = $this->db->prepare( $sql );                  // prepare sql
$query->bindParam( 'start', $start, PDO::PARAM_INT ); // bind start
$query->bindParam( 'end', $end, PDO::PARAM_INT );     // bind end
$query->bindParam( 'language', $this->language );     // bind language
$query->bindValue( 'keyword', "%$keyword%" );         // bind keyword

var_dump( $end );
$query->execute();
var_dump( $end );

输出

int 2
string '2' (length=1)

但是...如果我切换绑定的顺序...

$query = $this->db->prepare( $sql );                  // prepare sql
$query->bindParam( 'language', $this->language );     // bind language
$query->bindValue( 'keyword', "%$keyword%" );         // bind keyword
$query->bindParam( 'start', $start, PDO::PARAM_INT ); // bind start
$query->bindParam( 'end', $end, PDO::PARAM_INT );     // bind end

var_dump( $end );
$query->execute();
var_dump( $end );

输出

int 2
int 2

PHP 版本:Windows 上的 5.3.8

谁能解释为什么会这样?

4

3 回答 3

1

用 PHP 5.3.13 检查了这个 - 你的代码的两个版本给了我:

int 2
string '2' (length=1)

此外,使用 bindValue() 而不是 bindParam() 两个版本的代码给了我:

int 2
int 2

ps 我更喜欢使用 bindValue() 而不是将它与 bindParam() 混合使用。使用 bindParam() 不会带来任何性能改进。有些人认为 PHP 中的值传递和指针传递就像在 C/C++ 中一样,但这是错误的想法。使用 bindParam() 可能会导致错误发生时很难找到它们。

于 2015-03-30T17:11:23.650 回答
1

尝试转为准备陈述的仿真

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

于 2012-07-31T03:39:52.287 回答
-1

我知道这已经说过了,但我也会在上面写一个注释,因为我认为记住这一点很重要:

如果您使用 PDO bindParam 使用 LIKE 条件进行搜索,则不能将百分比和引号放入 param placeholder %:keyword%

这是错误的:

"SELECT * FROM `users` WHERE `firstname` LIKE '%:keyword%'";

正确的解决方案是让占位符保持清洁,如下所示:

"SELECT * FROM `users` WHERE `firstname` LIKE :keyword";

And then add the percentages to the php variable where you store the keyword:
$keyword = "%".$keyword."%";

最后,执行查询时 PDO 会自动添加引号,因此您不必担心它们。

所以完整的例子是:

<?php
    // Get the keyword from query string
    $keyword = $_GET['keyword'];
    // Prepare the command
    $sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
    // Put the percentage sing on the keyword
    $keyword = "%".$keyword."%";
    // Bind the parameter
    $sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);
?>
于 2015-03-30T13:04:55.473 回答